babylon.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339983409834198342983439834498345983469834798348983499835098351983529835398354983559835698357983589835998360983619836298363983649836598366983679836898369983709837198372983739837498375983769837798378983799838098381983829838398384983859838698387983889838998390983919839298393983949839598396983979839898399984009840198402984039840498405984069840798408984099841098411984129841398414984159841698417984189841998420984219842298423984249842598426984279842898429984309843198432984339843498435984369843798438984399844098441984429844398444984459844698447984489844998450984519845298453984549845598456984579845898459984609846198462984639846498465984669846798468984699847098471984729847398474984759847698477984789847998480984819848298483984849848598486984879848898489984909849198492984939849498495984969849798498984999850098501985029850398504985059850698507985089850998510985119851298513985149851598516985179851898519985209852198522985239852498525985269852798528985299853098531985329853398534985359853698537985389853998540985419854298543985449854598546985479854898549985509855198552985539855498555985569855798558985599856098561985629856398564985659856698567985689856998570985719857298573985749857598576985779857898579985809858198582985839858498585985869858798588985899859098591985929859398594985959859698597985989859998600986019860298603986049860598606986079860898609986109861198612986139861498615986169861798618986199862098621986229862398624986259862698627986289862998630
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  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. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. 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};
  29. 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)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * 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)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * 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)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * 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)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * 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)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * 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)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * 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)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * 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)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * 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)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * 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)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. _this.skipOnPointerObservable = false;
  1369. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1370. return _this;
  1371. }
  1372. return PointerInfoPre;
  1373. }(PointerInfoBase));
  1374. BABYLON.PointerInfoPre = PointerInfoPre;
  1375. /**
  1376. * This type contains all the data related to a pointer event in Babylon.js.
  1377. * 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.
  1378. */
  1379. var PointerInfo = /** @class */ (function (_super) {
  1380. __extends(PointerInfo, _super);
  1381. function PointerInfo(type, event, pickInfo) {
  1382. var _this = _super.call(this, type, event) || this;
  1383. _this.pickInfo = pickInfo;
  1384. return _this;
  1385. }
  1386. return PointerInfo;
  1387. }(PointerInfoBase));
  1388. BABYLON.PointerInfo = PointerInfo;
  1389. })(BABYLON || (BABYLON = {}));
  1390. //# sourceMappingURL=babylon.pointerEvents.js.map
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. BABYLON.ToGammaSpace = 1 / 2.2;
  1394. BABYLON.ToLinearSpace = 2.2;
  1395. BABYLON.Epsilon = 0.001;
  1396. /**
  1397. * Class used to hold a RBG color
  1398. */
  1399. var Color3 = /** @class */ (function () {
  1400. /**
  1401. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1402. * @param r defines the red component (between 0 and 1, default is 0)
  1403. * @param g defines the green component (between 0 and 1, default is 0)
  1404. * @param b defines the blue component (between 0 and 1, default is 0)
  1405. */
  1406. function Color3(
  1407. /**
  1408. * Defines the red component (between 0 and 1, default is 0)
  1409. */
  1410. r,
  1411. /**
  1412. * Defines the green component (between 0 and 1, default is 0)
  1413. */
  1414. g,
  1415. /**
  1416. * Defines the blue component (between 0 and 1, default is 0)
  1417. */
  1418. b) {
  1419. if (r === void 0) { r = 0; }
  1420. if (g === void 0) { g = 0; }
  1421. if (b === void 0) { b = 0; }
  1422. this.r = r;
  1423. this.g = g;
  1424. this.b = b;
  1425. }
  1426. /**
  1427. * Creates a string with the Color3 current values
  1428. * @returns the string representation of the Color3 object
  1429. */
  1430. Color3.prototype.toString = function () {
  1431. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1432. };
  1433. /**
  1434. * Returns the string "Color3"
  1435. * @returns "Color3"
  1436. */
  1437. Color3.prototype.getClassName = function () {
  1438. return "Color3";
  1439. };
  1440. /**
  1441. * Compute the Color3 hash code
  1442. * @returns an unique number that can be used to hash Color3 objects
  1443. */
  1444. Color3.prototype.getHashCode = function () {
  1445. var hash = this.r || 0;
  1446. hash = (hash * 397) ^ (this.g || 0);
  1447. hash = (hash * 397) ^ (this.b || 0);
  1448. return hash;
  1449. };
  1450. // Operators
  1451. /**
  1452. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1453. * @param array defines the array where to store the r,g,b components
  1454. * @param index defines an optional index in the target array to define where to start storing values
  1455. * @returns the current Color3 object
  1456. */
  1457. Color3.prototype.toArray = function (array, index) {
  1458. if (index === undefined) {
  1459. index = 0;
  1460. }
  1461. array[index] = this.r;
  1462. array[index + 1] = this.g;
  1463. array[index + 2] = this.b;
  1464. return this;
  1465. };
  1466. /**
  1467. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1468. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1469. * @returns a new {BABYLON.Color4} object
  1470. */
  1471. Color3.prototype.toColor4 = function (alpha) {
  1472. if (alpha === void 0) { alpha = 1; }
  1473. return new Color4(this.r, this.g, this.b, alpha);
  1474. };
  1475. /**
  1476. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1477. * @returns the new array
  1478. */
  1479. Color3.prototype.asArray = function () {
  1480. var result = new Array();
  1481. this.toArray(result, 0);
  1482. return result;
  1483. };
  1484. /**
  1485. * Returns the luminance value
  1486. * @returns a float value
  1487. */
  1488. Color3.prototype.toLuminance = function () {
  1489. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1490. };
  1491. /**
  1492. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1493. * @param otherColor defines the second operand
  1494. * @returns the new Color3 object
  1495. */
  1496. Color3.prototype.multiply = function (otherColor) {
  1497. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1498. };
  1499. /**
  1500. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1501. * @param otherColor defines the second operand
  1502. * @param result defines the Color3 object where to store the result
  1503. * @returns the current Color3
  1504. */
  1505. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1506. result.r = this.r * otherColor.r;
  1507. result.g = this.g * otherColor.g;
  1508. result.b = this.b * otherColor.b;
  1509. return this;
  1510. };
  1511. /**
  1512. * Determines equality between Color3 objects
  1513. * @param otherColor defines the second operand
  1514. * @returns true if the rgb values are equal to the given ones
  1515. */
  1516. Color3.prototype.equals = function (otherColor) {
  1517. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1518. };
  1519. /**
  1520. * Determines equality between the current Color3 object and a set of r,b,g values
  1521. * @param r defines the red component to check
  1522. * @param g defines the green component to check
  1523. * @param b defines the blue component to check
  1524. * @returns true if the rgb values are equal to the given ones
  1525. */
  1526. Color3.prototype.equalsFloats = function (r, g, b) {
  1527. return this.r === r && this.g === g && this.b === b;
  1528. };
  1529. /**
  1530. * Multiplies in place each rgb value by scale
  1531. * @param scale defines the scaling factor
  1532. * @returns the updated Color3
  1533. */
  1534. Color3.prototype.scale = function (scale) {
  1535. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1536. };
  1537. /**
  1538. * Multiplies the rgb values by scale and stores the result into "result"
  1539. * @param scale defines the scaling factor
  1540. * @param result defines the Color3 object where to store the result
  1541. * @returns the unmodified current Color3
  1542. */
  1543. Color3.prototype.scaleToRef = function (scale, result) {
  1544. result.r = this.r * scale;
  1545. result.g = this.g * scale;
  1546. result.b = this.b * scale;
  1547. return this;
  1548. };
  1549. /**
  1550. * Scale the current Color3 values by a factor and add the result to a given Color3
  1551. * @param scale defines the scale factor
  1552. * @param result defines color to store the result into
  1553. * @returns the unmodified current Color3
  1554. */
  1555. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1556. result.r += this.r * scale;
  1557. result.g += this.g * scale;
  1558. result.b += this.b * scale;
  1559. return this;
  1560. };
  1561. /**
  1562. * Clamps the rgb values by the min and max values and stores the result into "result"
  1563. * @param min defines minimum clamping value (default is 0)
  1564. * @param max defines maximum clamping value (default is 1)
  1565. * @param result defines color to store the result into
  1566. * @returns the original Color3
  1567. */
  1568. Color3.prototype.clampToRef = function (min, max, result) {
  1569. if (min === void 0) { min = 0; }
  1570. if (max === void 0) { max = 1; }
  1571. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1572. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1573. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1574. return this;
  1575. };
  1576. /**
  1577. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1578. * @param otherColor defines the second operand
  1579. * @returns the new Color3
  1580. */
  1581. Color3.prototype.add = function (otherColor) {
  1582. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1583. };
  1584. /**
  1585. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1586. * @param otherColor defines the second operand
  1587. * @param result defines Color3 object to store the result into
  1588. * @returns the unmodified current Color3
  1589. */
  1590. Color3.prototype.addToRef = function (otherColor, result) {
  1591. result.r = this.r + otherColor.r;
  1592. result.g = this.g + otherColor.g;
  1593. result.b = this.b + otherColor.b;
  1594. return this;
  1595. };
  1596. /**
  1597. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1598. * @param otherColor defines the second operand
  1599. * @returns the new Color3
  1600. */
  1601. Color3.prototype.subtract = function (otherColor) {
  1602. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1603. };
  1604. /**
  1605. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1606. * @param otherColor defines the second operand
  1607. * @param result defines Color3 object to store the result into
  1608. * @returns the unmodified current Color3
  1609. */
  1610. Color3.prototype.subtractToRef = function (otherColor, result) {
  1611. result.r = this.r - otherColor.r;
  1612. result.g = this.g - otherColor.g;
  1613. result.b = this.b - otherColor.b;
  1614. return this;
  1615. };
  1616. /**
  1617. * Copy the current object
  1618. * @returns a new Color3 copied the current one
  1619. */
  1620. Color3.prototype.clone = function () {
  1621. return new Color3(this.r, this.g, this.b);
  1622. };
  1623. /**
  1624. * Copies the rgb values from the source in the current Color3
  1625. * @param source defines the source Color3 object
  1626. * @returns the updated Color3 object
  1627. */
  1628. Color3.prototype.copyFrom = function (source) {
  1629. this.r = source.r;
  1630. this.g = source.g;
  1631. this.b = source.b;
  1632. return this;
  1633. };
  1634. /**
  1635. * Updates the Color3 rgb values from the given floats
  1636. * @param r defines the red component to read from
  1637. * @param g defines the green component to read from
  1638. * @param b defines the blue component to read from
  1639. * @returns the current Color3 object
  1640. */
  1641. Color3.prototype.copyFromFloats = function (r, g, b) {
  1642. this.r = r;
  1643. this.g = g;
  1644. this.b = b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Updates the Color3 rgb values from the given floats
  1649. * @param r defines the red component to read from
  1650. * @param g defines the green component to read from
  1651. * @param b defines the blue component to read from
  1652. * @returns the current Color3 object
  1653. */
  1654. Color3.prototype.set = function (r, g, b) {
  1655. return this.copyFromFloats(r, g, b);
  1656. };
  1657. /**
  1658. * Compute the Color3 hexadecimal code as a string
  1659. * @returns a string containing the hexadecimal representation of the Color3 object
  1660. */
  1661. Color3.prototype.toHexString = function () {
  1662. var intR = (this.r * 255) | 0;
  1663. var intG = (this.g * 255) | 0;
  1664. var intB = (this.b * 255) | 0;
  1665. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1666. };
  1667. /**
  1668. * Computes a new Color3 converted from the current one to linear space
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.prototype.toLinearSpace = function () {
  1672. var convertedColor = new Color3();
  1673. this.toLinearSpaceToRef(convertedColor);
  1674. return convertedColor;
  1675. };
  1676. /**
  1677. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1678. * @param convertedColor defines the Color3 object where to store the linear space version
  1679. * @returns the unmodified Color3
  1680. */
  1681. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1682. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1683. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1684. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1685. return this;
  1686. };
  1687. /**
  1688. * Computes a new Color3 converted from the current one to gamma space
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.prototype.toGammaSpace = function () {
  1692. var convertedColor = new Color3();
  1693. this.toGammaSpaceToRef(convertedColor);
  1694. return convertedColor;
  1695. };
  1696. /**
  1697. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1698. * @param convertedColor defines the Color3 object where to store the gamma space version
  1699. * @returns the unmodified Color3
  1700. */
  1701. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1702. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1703. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1704. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1705. return this;
  1706. };
  1707. // Statics
  1708. /**
  1709. * Creates a new Color3 from the string containing valid hexadecimal values
  1710. * @param hex defines a string containing valid hexadecimal values
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromHexString = function (hex) {
  1714. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1715. return new Color3(0, 0, 0);
  1716. }
  1717. var r = parseInt(hex.substring(1, 3), 16);
  1718. var g = parseInt(hex.substring(3, 5), 16);
  1719. var b = parseInt(hex.substring(5, 7), 16);
  1720. return Color3.FromInts(r, g, b);
  1721. };
  1722. /**
  1723. * Creates a new Vector3 from the starting index of the given array
  1724. * @param array defines the source array
  1725. * @param offset defines an offset in the source array
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromArray = function (array, offset) {
  1729. if (offset === void 0) { offset = 0; }
  1730. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1731. };
  1732. /**
  1733. * Creates a new Color3 from integer values (< 256)
  1734. * @param r defines the red component to read from (value between 0 and 255)
  1735. * @param g defines the green component to read from (value between 0 and 255)
  1736. * @param b defines the blue component to read from (value between 0 and 255)
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.FromInts = function (r, g, b) {
  1740. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1741. };
  1742. /**
  1743. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1744. * @param start defines the start Color3 value
  1745. * @param end defines the end Color3 value
  1746. * @param amount defines the gradient value between start and end
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Lerp = function (start, end, amount) {
  1750. var r = start.r + ((end.r - start.r) * amount);
  1751. var g = start.g + ((end.g - start.g) * amount);
  1752. var b = start.b + ((end.b - start.b) * amount);
  1753. return new Color3(r, g, b);
  1754. };
  1755. /**
  1756. * Returns a Color3 value containing a red color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Red = function () { return new Color3(1, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a green color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Green = function () { return new Color3(0, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a blue color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1770. /**
  1771. * Returns a Color3 value containing a black color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Black = function () { return new Color3(0, 0, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a white color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.White = function () { return new Color3(1, 1, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a purple color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a magenta color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a yellow color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a gray color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1800. /**
  1801. * Returns a Color3 value containing a teal color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1805. /**
  1806. * Returns a Color3 value containing a random color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1810. return Color3;
  1811. }());
  1812. BABYLON.Color3 = Color3;
  1813. /**
  1814. * Class used to hold a RBGA color
  1815. */
  1816. var Color4 = /** @class */ (function () {
  1817. /**
  1818. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1819. * @param r defines the red component (between 0 and 1, default is 0)
  1820. * @param g defines the green component (between 0 and 1, default is 0)
  1821. * @param b defines the blue component (between 0 and 1, default is 0)
  1822. * @param a defines the alpha component (between 0 and 1, default is 1)
  1823. */
  1824. function Color4(
  1825. /**
  1826. * Defines the red component (between 0 and 1, default is 0)
  1827. */
  1828. r,
  1829. /**
  1830. * Defines the green component (between 0 and 1, default is 0)
  1831. */
  1832. g,
  1833. /**
  1834. * Defines the blue component (between 0 and 1, default is 0)
  1835. */
  1836. b,
  1837. /**
  1838. * Defines the alpha component (between 0 and 1, default is 1)
  1839. */
  1840. a) {
  1841. if (r === void 0) { r = 0; }
  1842. if (g === void 0) { g = 0; }
  1843. if (b === void 0) { b = 0; }
  1844. if (a === void 0) { a = 1; }
  1845. this.r = r;
  1846. this.g = g;
  1847. this.b = b;
  1848. this.a = a;
  1849. }
  1850. // Operators
  1851. /**
  1852. * Adds in place the given Color4 values to the current Color4 object
  1853. * @param right defines the second operand
  1854. * @returns the current updated Color4 object
  1855. */
  1856. Color4.prototype.addInPlace = function (right) {
  1857. this.r += right.r;
  1858. this.g += right.g;
  1859. this.b += right.b;
  1860. this.a += right.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1865. * @returns the new array
  1866. */
  1867. Color4.prototype.asArray = function () {
  1868. var result = new Array();
  1869. this.toArray(result, 0);
  1870. return result;
  1871. };
  1872. /**
  1873. * Stores from the starting index in the given array the Color4 successive values
  1874. * @param array defines the array where to store the r,g,b components
  1875. * @param index defines an optional index in the target array to define where to start storing values
  1876. * @returns the current Color4 object
  1877. */
  1878. Color4.prototype.toArray = function (array, index) {
  1879. if (index === undefined) {
  1880. index = 0;
  1881. }
  1882. array[index] = this.r;
  1883. array[index + 1] = this.g;
  1884. array[index + 2] = this.b;
  1885. array[index + 3] = this.a;
  1886. return this;
  1887. };
  1888. /**
  1889. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1890. * @param right defines the second operand
  1891. * @returns a new Color4 object
  1892. */
  1893. Color4.prototype.add = function (right) {
  1894. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1895. };
  1896. /**
  1897. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1898. * @param right defines the second operand
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.subtract = function (right) {
  1902. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1903. };
  1904. /**
  1905. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1906. * @param right defines the second operand
  1907. * @param result defines the Color4 object where to store the result
  1908. * @returns the current Color4 object
  1909. */
  1910. Color4.prototype.subtractToRef = function (right, result) {
  1911. result.r = this.r - right.r;
  1912. result.g = this.g - right.g;
  1913. result.b = this.b - right.b;
  1914. result.a = this.a - right.a;
  1915. return this;
  1916. };
  1917. /**
  1918. * Creates a new Color4 with the current Color4 values multiplied by scale
  1919. * @param scale defines the scaling factor to apply
  1920. * @returns a new Color4 object
  1921. */
  1922. Color4.prototype.scale = function (scale) {
  1923. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1924. };
  1925. /**
  1926. * Multiplies the current Color4 values by scale and stores the result in "result"
  1927. * @param scale defines the scaling factor to apply
  1928. * @param result defines the Color4 object where to store the result
  1929. * @returns the current unmodified Color4
  1930. */
  1931. Color4.prototype.scaleToRef = function (scale, result) {
  1932. result.r = this.r * scale;
  1933. result.g = this.g * scale;
  1934. result.b = this.b * scale;
  1935. result.a = this.a * scale;
  1936. return this;
  1937. };
  1938. /**
  1939. * Scale the current Color4 values by a factor and add the result to a given Color4
  1940. * @param scale defines the scale factor
  1941. * @param result defines the Color4 object where to store the result
  1942. * @returns the unmodified current Color4
  1943. */
  1944. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1945. result.r += this.r * scale;
  1946. result.g += this.g * scale;
  1947. result.b += this.b * scale;
  1948. result.a += this.a * scale;
  1949. return this;
  1950. };
  1951. /**
  1952. * Clamps the rgb values by the min and max values and stores the result into "result"
  1953. * @param min defines minimum clamping value (default is 0)
  1954. * @param max defines maximum clamping value (default is 1)
  1955. * @param result defines color to store the result into.
  1956. * @returns the cuurent Color4
  1957. */
  1958. Color4.prototype.clampToRef = function (min, max, result) {
  1959. if (min === void 0) { min = 0; }
  1960. if (max === void 0) { max = 1; }
  1961. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1962. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1963. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1964. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1965. return this;
  1966. };
  1967. /**
  1968. * Multipy an Color4 value by another and return a new Color4 object
  1969. * @param color defines the Color4 value to multiply by
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.multiply = function (color) {
  1973. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1974. };
  1975. /**
  1976. * Multipy a Color4 value by another and push the result in a reference value
  1977. * @param color defines the Color4 value to multiply by
  1978. * @param result defines the Color4 to fill the result in
  1979. * @returns the result Color4
  1980. */
  1981. Color4.prototype.multiplyToRef = function (color, result) {
  1982. result.r = this.r * color.r;
  1983. result.g = this.g * color.g;
  1984. result.b = this.b * color.b;
  1985. result.a = this.a * color.a;
  1986. return result;
  1987. };
  1988. /**
  1989. * Creates a string with the Color4 current values
  1990. * @returns the string representation of the Color4 object
  1991. */
  1992. Color4.prototype.toString = function () {
  1993. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1994. };
  1995. /**
  1996. * Returns the string "Color4"
  1997. * @returns "Color4"
  1998. */
  1999. Color4.prototype.getClassName = function () {
  2000. return "Color4";
  2001. };
  2002. /**
  2003. * Compute the Color4 hash code
  2004. * @returns an unique number that can be used to hash Color4 objects
  2005. */
  2006. Color4.prototype.getHashCode = function () {
  2007. var hash = this.r || 0;
  2008. hash = (hash * 397) ^ (this.g || 0);
  2009. hash = (hash * 397) ^ (this.b || 0);
  2010. hash = (hash * 397) ^ (this.a || 0);
  2011. return hash;
  2012. };
  2013. /**
  2014. * Creates a new Color4 copied from the current one
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.clone = function () {
  2018. return new Color4(this.r, this.g, this.b, this.a);
  2019. };
  2020. /**
  2021. * Copies the given Color4 values into the current one
  2022. * @param source defines the source Color4 object
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.copyFrom = function (source) {
  2026. this.r = source.r;
  2027. this.g = source.g;
  2028. this.b = source.b;
  2029. this.a = source.a;
  2030. return this;
  2031. };
  2032. /**
  2033. * Copies the given float values into the current one
  2034. * @param r defines the red component to read from
  2035. * @param g defines the green component to read from
  2036. * @param b defines the blue component to read from
  2037. * @param a defines the alpha component to read from
  2038. * @returns the current updated Color4 object
  2039. */
  2040. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2041. this.r = r;
  2042. this.g = g;
  2043. this.b = b;
  2044. this.a = a;
  2045. return this;
  2046. };
  2047. /**
  2048. * Copies the given float values into the current one
  2049. * @param r defines the red component to read from
  2050. * @param g defines the green component to read from
  2051. * @param b defines the blue component to read from
  2052. * @param a defines the alpha component to read from
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.set = function (r, g, b, a) {
  2056. return this.copyFromFloats(r, g, b, a);
  2057. };
  2058. /**
  2059. * Compute the Color4 hexadecimal code as a string
  2060. * @returns a string containing the hexadecimal representation of the Color4 object
  2061. */
  2062. Color4.prototype.toHexString = function () {
  2063. var intR = (this.r * 255) | 0;
  2064. var intG = (this.g * 255) | 0;
  2065. var intB = (this.b * 255) | 0;
  2066. var intA = (this.a * 255) | 0;
  2067. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2068. };
  2069. /**
  2070. * Computes a new Color4 converted from the current one to linear space
  2071. * @returns a new Color4 object
  2072. */
  2073. Color4.prototype.toLinearSpace = function () {
  2074. var convertedColor = new Color4();
  2075. this.toLinearSpaceToRef(convertedColor);
  2076. return convertedColor;
  2077. };
  2078. /**
  2079. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2080. * @param convertedColor defines the Color4 object where to store the linear space version
  2081. * @returns the unmodified Color4
  2082. */
  2083. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2084. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2085. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2086. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2087. convertedColor.a = this.a;
  2088. return this;
  2089. };
  2090. /**
  2091. * Computes a new Color4 converted from the current one to gamma space
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.toGammaSpace = function () {
  2095. var convertedColor = new Color4();
  2096. this.toGammaSpaceToRef(convertedColor);
  2097. return convertedColor;
  2098. };
  2099. /**
  2100. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2101. * @param convertedColor defines the Color4 object where to store the gamma space version
  2102. * @returns the unmodified Color4
  2103. */
  2104. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2105. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2106. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2107. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2108. convertedColor.a = this.a;
  2109. return this;
  2110. };
  2111. // Statics
  2112. /**
  2113. * Creates a new Color4 from the string containing valid hexadecimal values
  2114. * @param hex defines a string containing valid hexadecimal values
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.FromHexString = function (hex) {
  2118. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2119. return new Color4(0.0, 0.0, 0.0, 0.0);
  2120. }
  2121. var r = parseInt(hex.substring(1, 3), 16);
  2122. var g = parseInt(hex.substring(3, 5), 16);
  2123. var b = parseInt(hex.substring(5, 7), 16);
  2124. var a = parseInt(hex.substring(7, 9), 16);
  2125. return Color4.FromInts(r, g, b, a);
  2126. };
  2127. /**
  2128. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2129. * @param left defines the start value
  2130. * @param right defines the end value
  2131. * @param amount defines the gradient factor
  2132. * @returns a new Color4 object
  2133. */
  2134. Color4.Lerp = function (left, right, amount) {
  2135. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2136. Color4.LerpToRef(left, right, amount, result);
  2137. return result;
  2138. };
  2139. /**
  2140. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2141. * @param left defines the start value
  2142. * @param right defines the end value
  2143. * @param amount defines the gradient factor
  2144. * @param result defines the Color4 object where to store data
  2145. */
  2146. Color4.LerpToRef = function (left, right, amount, result) {
  2147. result.r = left.r + (right.r - left.r) * amount;
  2148. result.g = left.g + (right.g - left.g) * amount;
  2149. result.b = left.b + (right.b - left.b) * amount;
  2150. result.a = left.a + (right.a - left.a) * amount;
  2151. };
  2152. /**
  2153. * Creates a new Color4 from the starting index element of the given array
  2154. * @param array defines the source array to read from
  2155. * @param offset defines the offset in the source array
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromArray = function (array, offset) {
  2159. if (offset === void 0) { offset = 0; }
  2160. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2161. };
  2162. /**
  2163. * Creates a new Color3 from integer values (< 256)
  2164. * @param r defines the red component to read from (value between 0 and 255)
  2165. * @param g defines the green component to read from (value between 0 and 255)
  2166. * @param b defines the blue component to read from (value between 0 and 255)
  2167. * @param a defines the alpha component to read from (value between 0 and 255)
  2168. * @returns a new Color3 object
  2169. */
  2170. Color4.FromInts = function (r, g, b, a) {
  2171. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2172. };
  2173. /**
  2174. * Check the content of a given array and convert it to an array containing RGBA data
  2175. * If the original array was already containing count * 4 values then it is returned directly
  2176. * @param colors defines the array to check
  2177. * @param count defines the number of RGBA data to expect
  2178. * @returns an array containing count * 4 values (RGBA)
  2179. */
  2180. Color4.CheckColors4 = function (colors, count) {
  2181. // Check if color3 was used
  2182. if (colors.length === count * 3) {
  2183. var colors4 = [];
  2184. for (var index = 0; index < colors.length; index += 3) {
  2185. var newIndex = (index / 3) * 4;
  2186. colors4[newIndex] = colors[index];
  2187. colors4[newIndex + 1] = colors[index + 1];
  2188. colors4[newIndex + 2] = colors[index + 2];
  2189. colors4[newIndex + 3] = 1.0;
  2190. }
  2191. return colors4;
  2192. }
  2193. return colors;
  2194. };
  2195. return Color4;
  2196. }());
  2197. BABYLON.Color4 = Color4;
  2198. /**
  2199. * Class representing a vector containing 2 coordinates
  2200. */
  2201. var Vector2 = /** @class */ (function () {
  2202. /**
  2203. * Creates a new Vector2 from the given x and y coordinates
  2204. * @param x defines the first coordinate
  2205. * @param y defines the second coordinate
  2206. */
  2207. function Vector2(
  2208. /** defines the first coordinate */
  2209. x,
  2210. /** defines the second coordinate */
  2211. y) {
  2212. this.x = x;
  2213. this.y = y;
  2214. }
  2215. /**
  2216. * Gets a string with the Vector2 coordinates
  2217. * @returns a string with the Vector2 coordinates
  2218. */
  2219. Vector2.prototype.toString = function () {
  2220. return "{X: " + this.x + " Y:" + this.y + "}";
  2221. };
  2222. /**
  2223. * Gets class name
  2224. * @returns the string "Vector2"
  2225. */
  2226. Vector2.prototype.getClassName = function () {
  2227. return "Vector2";
  2228. };
  2229. /**
  2230. * Gets current vector hash code
  2231. * @returns the Vector2 hash code as a number
  2232. */
  2233. Vector2.prototype.getHashCode = function () {
  2234. var hash = this.x || 0;
  2235. hash = (hash * 397) ^ (this.y || 0);
  2236. return hash;
  2237. };
  2238. // Operators
  2239. /**
  2240. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2241. * @param array defines the source array
  2242. * @param index defines the offset in source array
  2243. * @returns the current Vector2
  2244. */
  2245. Vector2.prototype.toArray = function (array, index) {
  2246. if (index === void 0) { index = 0; }
  2247. array[index] = this.x;
  2248. array[index + 1] = this.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Copy the current vector to an array
  2253. * @returns a new array with 2 elements: the Vector2 coordinates.
  2254. */
  2255. Vector2.prototype.asArray = function () {
  2256. var result = new Array();
  2257. this.toArray(result, 0);
  2258. return result;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2262. * @param source defines the source Vector2
  2263. * @returns the current updated Vector2
  2264. */
  2265. Vector2.prototype.copyFrom = function (source) {
  2266. this.x = source.x;
  2267. this.y = source.y;
  2268. return this;
  2269. };
  2270. /**
  2271. * Sets the Vector2 coordinates with the given floats
  2272. * @param x defines the first coordinate
  2273. * @param y defines the second coordinate
  2274. * @returns the current updated Vector2
  2275. */
  2276. Vector2.prototype.copyFromFloats = function (x, y) {
  2277. this.x = x;
  2278. this.y = y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Sets the Vector2 coordinates with the given floats
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.set = function (x, y) {
  2288. return this.copyFromFloats(x, y);
  2289. };
  2290. /**
  2291. * Add another vector with the current one
  2292. * @param otherVector defines the other vector
  2293. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2294. */
  2295. Vector2.prototype.add = function (otherVector) {
  2296. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2297. };
  2298. /**
  2299. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2300. * @param otherVector defines the other vector
  2301. * @param result defines the target vector
  2302. * @returns the unmodified current Vector2
  2303. */
  2304. Vector2.prototype.addToRef = function (otherVector, result) {
  2305. result.x = this.x + otherVector.x;
  2306. result.y = this.y + otherVector.y;
  2307. return this;
  2308. };
  2309. /**
  2310. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2311. * @param otherVector defines the other vector
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.addInPlace = function (otherVector) {
  2315. this.x += otherVector.x;
  2316. this.y += otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns a new Vector2
  2323. */
  2324. Vector2.prototype.addVector3 = function (otherVector) {
  2325. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2326. };
  2327. /**
  2328. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2329. * @param otherVector defines the other vector
  2330. * @returns a new Vector2
  2331. */
  2332. Vector2.prototype.subtract = function (otherVector) {
  2333. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2337. * @param otherVector defines the other vector
  2338. * @param result defines the target vector
  2339. * @returns the unmodified current Vector2
  2340. */
  2341. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2342. result.x = this.x - otherVector.x;
  2343. result.y = this.y - otherVector.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2348. * @param otherVector defines the other vector
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.subtractInPlace = function (otherVector) {
  2352. this.x -= otherVector.x;
  2353. this.y -= otherVector.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Multiplies in place the current Vector2 coordinates by the given ones
  2358. * @param otherVector defines the other vector
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2362. this.x *= otherVector.x;
  2363. this.y *= otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2368. * @param otherVector defines the other vector
  2369. * @returns a new Vector2
  2370. */
  2371. Vector2.prototype.multiply = function (otherVector) {
  2372. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2373. };
  2374. /**
  2375. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2376. * @param otherVector defines the other vector
  2377. * @param result defines the target vector
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2381. result.x = this.x * otherVector.x;
  2382. result.y = this.y * otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2387. * @param x defines the first coordinate
  2388. * @param y defines the second coordinate
  2389. * @returns a new Vector2
  2390. */
  2391. Vector2.prototype.multiplyByFloats = function (x, y) {
  2392. return new Vector2(this.x * x, this.y * y);
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2396. * @param otherVector defines the other vector
  2397. * @returns a new Vector2
  2398. */
  2399. Vector2.prototype.divide = function (otherVector) {
  2400. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2401. };
  2402. /**
  2403. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2404. * @param otherVector defines the other vector
  2405. * @param result defines the target vector
  2406. * @returns the unmodified current Vector2
  2407. */
  2408. Vector2.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. return this;
  2412. };
  2413. /**
  2414. * Divides the current Vector3 coordinates by the given ones
  2415. * @param otherVector defines the other vector
  2416. * @returns the current updated Vector2
  2417. */
  2418. Vector2.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Gets a new Vector2 with current Vector2 negated coordinates
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.negate = function () {
  2426. return new Vector2(-this.x, -this.y);
  2427. };
  2428. /**
  2429. * Multiply the Vector2 coordinates by scale
  2430. * @param scale defines the scaling factor
  2431. * @returns the current updated Vector2
  2432. */
  2433. Vector2.prototype.scaleInPlace = function (scale) {
  2434. this.x *= scale;
  2435. this.y *= scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2440. * @param scale defines the scaling factor
  2441. * @returns a new Vector2
  2442. */
  2443. Vector2.prototype.scale = function (scale) {
  2444. var result = new Vector2(0, 0);
  2445. this.scaleToRef(scale, result);
  2446. return result;
  2447. };
  2448. /**
  2449. * Scale the current Vector2 values by a factor to a given Vector2
  2450. * @param scale defines the scale factor
  2451. * @param result defines the Vector2 object where to store the result
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.scaleToRef = function (scale, result) {
  2455. result.x = this.x * scale;
  2456. result.y = this.y * scale;
  2457. return this;
  2458. };
  2459. /**
  2460. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2461. * @param scale defines the scale factor
  2462. * @param result defines the Vector2 object where to store the result
  2463. * @returns the unmodified current Vector2
  2464. */
  2465. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2466. result.x += this.x * scale;
  2467. result.y += this.y * scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Gets a boolean if two vectors are equals
  2472. * @param otherVector defines the other vector
  2473. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2474. */
  2475. Vector2.prototype.equals = function (otherVector) {
  2476. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2477. };
  2478. /**
  2479. * Gets a boolean if two vectors are equals (using an epsilon value)
  2480. * @param otherVector defines the other vector
  2481. * @param epsilon defines the minimal distance to consider equality
  2482. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2483. */
  2484. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2485. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2486. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2487. };
  2488. // Properties
  2489. /**
  2490. * Gets the length of the vector
  2491. * @returns the vector length (float)
  2492. */
  2493. Vector2.prototype.length = function () {
  2494. return Math.sqrt(this.x * this.x + this.y * this.y);
  2495. };
  2496. /**
  2497. * Gets the vector squared length
  2498. * @returns the vector squared length (float)
  2499. */
  2500. Vector2.prototype.lengthSquared = function () {
  2501. return (this.x * this.x + this.y * this.y);
  2502. };
  2503. // Methods
  2504. /**
  2505. * Normalize the vector
  2506. * @returns the current updated Vector2
  2507. */
  2508. Vector2.prototype.normalize = function () {
  2509. var len = this.length();
  2510. if (len === 0)
  2511. return this;
  2512. var num = 1.0 / len;
  2513. this.x *= num;
  2514. this.y *= num;
  2515. return this;
  2516. };
  2517. /**
  2518. * Gets a new Vector2 copied from the Vector2
  2519. * @returns a new Vector2
  2520. */
  2521. Vector2.prototype.clone = function () {
  2522. return new Vector2(this.x, this.y);
  2523. };
  2524. // Statics
  2525. /**
  2526. * Gets a new Vector2(0, 0)
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.Zero = function () {
  2530. return new Vector2(0, 0);
  2531. };
  2532. /**
  2533. * Gets a new Vector2(1, 1)
  2534. * @returns a new Vector2
  2535. */
  2536. Vector2.One = function () {
  2537. return new Vector2(1, 1);
  2538. };
  2539. /**
  2540. * Gets a new Vector2 set from the given index element of the given array
  2541. * @param array defines the data source
  2542. * @param offset defines the offset in the data source
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.FromArray = function (array, offset) {
  2546. if (offset === void 0) { offset = 0; }
  2547. return new Vector2(array[offset], array[offset + 1]);
  2548. };
  2549. /**
  2550. * Sets "result" from the given index element of the given array
  2551. * @param array defines the data source
  2552. * @param offset defines the offset in the data source
  2553. * @param result defines the target vector
  2554. */
  2555. Vector2.FromArrayToRef = function (array, offset, result) {
  2556. result.x = array[offset];
  2557. result.y = array[offset + 1];
  2558. };
  2559. /**
  2560. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2561. * @param value1 defines 1st point of control
  2562. * @param value2 defines 2nd point of control
  2563. * @param value3 defines 3rd point of control
  2564. * @param value4 defines 4th point of control
  2565. * @param amount defines the interpolation factor
  2566. * @returns a new Vector2
  2567. */
  2568. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2569. var squared = amount * amount;
  2570. var cubed = amount * squared;
  2571. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2572. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2573. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2574. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2575. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2576. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2577. return new Vector2(x, y);
  2578. };
  2579. /**
  2580. * 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".
  2581. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2582. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2583. * @param value defines the value to clamp
  2584. * @param min defines the lower limit
  2585. * @param max defines the upper limit
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.Clamp = function (value, min, max) {
  2589. var x = value.x;
  2590. x = (x > max.x) ? max.x : x;
  2591. x = (x < min.x) ? min.x : x;
  2592. var y = value.y;
  2593. y = (y > max.y) ? max.y : y;
  2594. y = (y < min.y) ? min.y : y;
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2599. * @param value1 defines the 1st control point
  2600. * @param tangent1 defines the outgoing tangent
  2601. * @param value2 defines the 2nd control point
  2602. * @param tangent2 defines the incoming tangent
  2603. * @param amount defines the interpolation factor
  2604. * @returns a new Vector2
  2605. */
  2606. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2607. var squared = amount * amount;
  2608. var cubed = amount * squared;
  2609. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2610. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2611. var part3 = (cubed - (2.0 * squared)) + amount;
  2612. var part4 = cubed - squared;
  2613. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2614. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2615. return new Vector2(x, y);
  2616. };
  2617. /**
  2618. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2619. * @param start defines the start vector
  2620. * @param end defines the end vector
  2621. * @param amount defines the interpolation factor
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Lerp = function (start, end, amount) {
  2625. var x = start.x + ((end.x - start.x) * amount);
  2626. var y = start.y + ((end.y - start.y) * amount);
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets the dot product of the vector "left" and the vector "right"
  2631. * @param left defines first vector
  2632. * @param right defines second vector
  2633. * @returns the dot product (float)
  2634. */
  2635. Vector2.Dot = function (left, right) {
  2636. return left.x * right.x + left.y * right.y;
  2637. };
  2638. /**
  2639. * Returns a new Vector2 equal to the normalized given vector
  2640. * @param vector defines the vector to normalize
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Normalize = function (vector) {
  2644. var newVector = vector.clone();
  2645. newVector.normalize();
  2646. return newVector;
  2647. };
  2648. /**
  2649. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2650. * @param left defines 1st vector
  2651. * @param right defines 2nd vector
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.Minimize = function (left, right) {
  2655. var x = (left.x < right.x) ? left.x : right.x;
  2656. var y = (left.y < right.y) ? left.y : right.y;
  2657. return new Vector2(x, y);
  2658. };
  2659. /**
  2660. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2661. * @param left defines 1st vector
  2662. * @param right defines 2nd vector
  2663. * @returns a new Vector2
  2664. */
  2665. Vector2.Maximize = function (left, right) {
  2666. var x = (left.x > right.x) ? left.x : right.x;
  2667. var y = (left.y > right.y) ? left.y : right.y;
  2668. return new Vector2(x, y);
  2669. };
  2670. /**
  2671. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2672. * @param vector defines the vector to transform
  2673. * @param transformation defines the matrix to apply
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Transform = function (vector, transformation) {
  2677. var r = Vector2.Zero();
  2678. Vector2.TransformToRef(vector, transformation, r);
  2679. return r;
  2680. };
  2681. /**
  2682. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2683. * @param vector defines the vector to transform
  2684. * @param transformation defines the matrix to apply
  2685. * @param result defines the target vector
  2686. */
  2687. Vector2.TransformToRef = function (vector, transformation, result) {
  2688. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2689. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2690. result.x = x;
  2691. result.y = y;
  2692. };
  2693. /**
  2694. * Determines if a given vector is included in a triangle
  2695. * @param p defines the vector to test
  2696. * @param p0 defines 1st triangle point
  2697. * @param p1 defines 2nd triangle point
  2698. * @param p2 defines 3rd triangle point
  2699. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2700. */
  2701. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2702. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2703. var sign = a < 0 ? -1 : 1;
  2704. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2705. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2706. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2707. };
  2708. /**
  2709. * Gets the distance between the vectors "value1" and "value2"
  2710. * @param value1 defines first vector
  2711. * @param value2 defines second vector
  2712. * @returns the distance between vectors
  2713. */
  2714. Vector2.Distance = function (value1, value2) {
  2715. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2716. };
  2717. /**
  2718. * Returns the squared distance between the vectors "value1" and "value2"
  2719. * @param value1 defines first vector
  2720. * @param value2 defines second vector
  2721. * @returns the squared distance between vectors
  2722. */
  2723. Vector2.DistanceSquared = function (value1, value2) {
  2724. var x = value1.x - value2.x;
  2725. var y = value1.y - value2.y;
  2726. return (x * x) + (y * y);
  2727. };
  2728. /**
  2729. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2730. * @param value1 defines first vector
  2731. * @param value2 defines second vector
  2732. * @returns a new Vector2
  2733. */
  2734. Vector2.Center = function (value1, value2) {
  2735. var center = value1.add(value2);
  2736. center.scaleInPlace(0.5);
  2737. return center;
  2738. };
  2739. /**
  2740. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2741. * @param p defines the middle point
  2742. * @param segA defines one point of the segment
  2743. * @param segB defines the other point of the segment
  2744. * @returns the shortest distance
  2745. */
  2746. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2747. var l2 = Vector2.DistanceSquared(segA, segB);
  2748. if (l2 === 0.0) {
  2749. return Vector2.Distance(p, segA);
  2750. }
  2751. var v = segB.subtract(segA);
  2752. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2753. var proj = segA.add(v.multiplyByFloats(t, t));
  2754. return Vector2.Distance(p, proj);
  2755. };
  2756. return Vector2;
  2757. }());
  2758. BABYLON.Vector2 = Vector2;
  2759. /**
  2760. * Classed used to store (x,y,z) vector representation
  2761. * A Vector3 is the main object used in 3D geometry
  2762. * It can represent etiher the coordinates of a point the space, either a direction
  2763. * Reminder: Babylon.js uses a left handed forward facing system
  2764. */
  2765. var Vector3 = /** @class */ (function () {
  2766. /**
  2767. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2768. * @param x defines the first coordinates (on X axis)
  2769. * @param y defines the second coordinates (on Y axis)
  2770. * @param z defines the third coordinates (on Z axis)
  2771. */
  2772. function Vector3(
  2773. /**
  2774. * Defines the first coordinates (on X axis)
  2775. */
  2776. x,
  2777. /**
  2778. * Defines the second coordinates (on Y axis)
  2779. */
  2780. y,
  2781. /**
  2782. * Defines the third coordinates (on Z axis)
  2783. */
  2784. z) {
  2785. this.x = x;
  2786. this.y = y;
  2787. this.z = z;
  2788. }
  2789. /**
  2790. * Creates a string representation of the Vector3
  2791. * @returns a string with the Vector3 coordinates.
  2792. */
  2793. Vector3.prototype.toString = function () {
  2794. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2795. };
  2796. /**
  2797. * Gets the class name
  2798. * @returns the string "Vector3"
  2799. */
  2800. Vector3.prototype.getClassName = function () {
  2801. return "Vector3";
  2802. };
  2803. /**
  2804. * Creates the Vector3 hash code
  2805. * @returns a number which tends to be unique between Vector3 instances
  2806. */
  2807. Vector3.prototype.getHashCode = function () {
  2808. var hash = this.x || 0;
  2809. hash = (hash * 397) ^ (this.y || 0);
  2810. hash = (hash * 397) ^ (this.z || 0);
  2811. return hash;
  2812. };
  2813. // Operators
  2814. /**
  2815. * Creates an array containing three elements : the coordinates of the Vector3
  2816. * @returns a new array of numbers
  2817. */
  2818. Vector3.prototype.asArray = function () {
  2819. var result = [];
  2820. this.toArray(result, 0);
  2821. return result;
  2822. };
  2823. /**
  2824. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2825. * @param array defines the destination array
  2826. * @param index defines the offset in the destination array
  2827. * @returns the current Vector3
  2828. */
  2829. Vector3.prototype.toArray = function (array, index) {
  2830. if (index === void 0) { index = 0; }
  2831. array[index] = this.x;
  2832. array[index + 1] = this.y;
  2833. array[index + 2] = this.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2838. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2839. */
  2840. Vector3.prototype.toQuaternion = function () {
  2841. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2842. };
  2843. /**
  2844. * Adds the given vector to the current Vector3
  2845. * @param otherVector defines the second operand
  2846. * @returns the current updated Vector3
  2847. */
  2848. Vector3.prototype.addInPlace = function (otherVector) {
  2849. this.x += otherVector.x;
  2850. this.y += otherVector.y;
  2851. this.z += otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2856. * @param otherVector defines the second operand
  2857. * @returns the resulting Vector3
  2858. */
  2859. Vector3.prototype.add = function (otherVector) {
  2860. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2861. };
  2862. /**
  2863. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2864. * @param otherVector defines the second operand
  2865. * @param result defines the Vector3 object where to store the result
  2866. * @returns the current Vector3
  2867. */
  2868. Vector3.prototype.addToRef = function (otherVector, result) {
  2869. result.x = this.x + otherVector.x;
  2870. result.y = this.y + otherVector.y;
  2871. result.z = this.z + otherVector.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Subtract the given vector from the current Vector3
  2876. * @param otherVector defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.subtractInPlace = function (otherVector) {
  2880. this.x -= otherVector.x;
  2881. this.y -= otherVector.y;
  2882. this.z -= otherVector.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2887. * @param otherVector defines the second operand
  2888. * @returns the resulting Vector3
  2889. */
  2890. Vector3.prototype.subtract = function (otherVector) {
  2891. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2892. };
  2893. /**
  2894. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2895. * @param otherVector defines the second operand
  2896. * @param result defines the Vector3 object where to store the result
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2900. result.x = this.x - otherVector.x;
  2901. result.y = this.y - otherVector.y;
  2902. result.z = this.z - otherVector.z;
  2903. return this;
  2904. };
  2905. /**
  2906. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2907. * @param x defines the x coordinate of the operand
  2908. * @param y defines the y coordinate of the operand
  2909. * @param z defines the z coordinate of the operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2913. return new Vector3(this.x - x, this.y - y, this.z - z);
  2914. };
  2915. /**
  2916. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2917. * @param x defines the x coordinate of the operand
  2918. * @param y defines the y coordinate of the operand
  2919. * @param z defines the z coordinate of the operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2924. result.x = this.x - x;
  2925. result.y = this.y - y;
  2926. result.z = this.z - z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2931. * @returns a new Vector3
  2932. */
  2933. Vector3.prototype.negate = function () {
  2934. return new Vector3(-this.x, -this.y, -this.z);
  2935. };
  2936. /**
  2937. * Multiplies the Vector3 coordinates by the float "scale"
  2938. * @param scale defines the multiplier factor
  2939. * @returns the current updated Vector3
  2940. */
  2941. Vector3.prototype.scaleInPlace = function (scale) {
  2942. this.x *= scale;
  2943. this.y *= scale;
  2944. this.z *= scale;
  2945. return this;
  2946. };
  2947. /**
  2948. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2949. * @param scale defines the multiplier factor
  2950. * @returns a new Vector3
  2951. */
  2952. Vector3.prototype.scale = function (scale) {
  2953. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2954. };
  2955. /**
  2956. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2957. * @param scale defines the multiplier factor
  2958. * @param result defines the Vector3 object where to store the result
  2959. * @returns the current Vector3
  2960. */
  2961. Vector3.prototype.scaleToRef = function (scale, result) {
  2962. result.x = this.x * scale;
  2963. result.y = this.y * scale;
  2964. result.z = this.z * scale;
  2965. return this;
  2966. };
  2967. /**
  2968. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2969. * @param scale defines the scale factor
  2970. * @param result defines the Vector3 object where to store the result
  2971. * @returns the unmodified current Vector3
  2972. */
  2973. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2974. result.x += this.x * scale;
  2975. result.y += this.y * scale;
  2976. result.z += this.z * scale;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2981. * @param otherVector defines the second operand
  2982. * @returns true if both vectors are equals
  2983. */
  2984. Vector3.prototype.equals = function (otherVector) {
  2985. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2986. };
  2987. /**
  2988. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2989. * @param otherVector defines the second operand
  2990. * @param epsilon defines the minimal distance to define values as equals
  2991. * @returns true if both vectors are distant less than epsilon
  2992. */
  2993. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2994. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2995. 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);
  2996. };
  2997. /**
  2998. * Returns true if the current Vector3 coordinates equals the given floats
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @returns true if both vectors are equals
  3003. */
  3004. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3005. return this.x === x && this.y === y && this.z === z;
  3006. };
  3007. /**
  3008. * Multiplies the current Vector3 coordinates by the given ones
  3009. * @param otherVector defines the second operand
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3013. this.x *= otherVector.x;
  3014. this.y *= otherVector.y;
  3015. this.z *= otherVector.z;
  3016. return this;
  3017. };
  3018. /**
  3019. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.multiply = function (otherVector) {
  3024. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3025. };
  3026. /**
  3027. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3033. result.x = this.x * otherVector.x;
  3034. result.y = this.y * otherVector.y;
  3035. result.z = this.z * otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3046. return new Vector3(this.x * x, this.y * y, this.z * z);
  3047. };
  3048. /**
  3049. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3050. * @param otherVector defines the second operand
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.divide = function (otherVector) {
  3054. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3055. };
  3056. /**
  3057. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3058. * @param otherVector defines the second operand
  3059. * @param result defines the Vector3 object where to store the result
  3060. * @returns the current Vector3
  3061. */
  3062. Vector3.prototype.divideToRef = function (otherVector, result) {
  3063. result.x = this.x / otherVector.x;
  3064. result.y = this.y / otherVector.y;
  3065. result.z = this.z / otherVector.z;
  3066. return this;
  3067. };
  3068. /**
  3069. * Divides the current Vector3 coordinates by the given ones.
  3070. * @param otherVector defines the second operand
  3071. * @returns the current updated Vector3
  3072. */
  3073. Vector3.prototype.divideInPlace = function (otherVector) {
  3074. return this.divideToRef(otherVector, this);
  3075. };
  3076. /**
  3077. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3078. * @param other defines the second operand
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.minimizeInPlace = function (other) {
  3082. if (other.x < this.x)
  3083. this.x = other.x;
  3084. if (other.y < this.y)
  3085. this.y = other.y;
  3086. if (other.z < this.z)
  3087. this.z = other.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3092. * @param other defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.maximizeInPlace = function (other) {
  3096. if (other.x > this.x)
  3097. this.x = other.x;
  3098. if (other.y > this.y)
  3099. this.y = other.y;
  3100. if (other.z > this.z)
  3101. this.z = other.z;
  3102. return this;
  3103. };
  3104. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3105. /**
  3106. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3107. */
  3108. get: function () {
  3109. var absX = Math.abs(this.x);
  3110. var absY = Math.abs(this.y);
  3111. if (absX !== absY) {
  3112. return true;
  3113. }
  3114. var absZ = Math.abs(this.z);
  3115. if (absX !== absZ) {
  3116. return true;
  3117. }
  3118. if (absY !== absZ) {
  3119. return true;
  3120. }
  3121. return false;
  3122. },
  3123. enumerable: true,
  3124. configurable: true
  3125. });
  3126. // Properties
  3127. /**
  3128. * Gets the length of the Vector3
  3129. * @returns the length of the Vecto3
  3130. */
  3131. Vector3.prototype.length = function () {
  3132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3133. };
  3134. /**
  3135. * Gets the squared length of the Vector3
  3136. * @returns squared length of the Vector3
  3137. */
  3138. Vector3.prototype.lengthSquared = function () {
  3139. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3140. };
  3141. /**
  3142. * Normalize the current Vector3.
  3143. * Please note that this is an in place operation.
  3144. * @returns the current updated Vector3
  3145. */
  3146. Vector3.prototype.normalize = function () {
  3147. var len = this.length();
  3148. if (len === 0 || len === 1.0)
  3149. return this;
  3150. var num = 1.0 / len;
  3151. this.x *= num;
  3152. this.y *= num;
  3153. this.z *= num;
  3154. return this;
  3155. };
  3156. /**
  3157. * Normalize the current Vector3 to a new vector
  3158. * @returns the new Vector3
  3159. */
  3160. Vector3.prototype.normalizeToNew = function () {
  3161. var normalized = new Vector3(0, 0, 0);
  3162. this.normalizeToRef(normalized);
  3163. return normalized;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to the reference
  3167. * @param reference define the Vector3 to update
  3168. * @returns the updated Vector3
  3169. */
  3170. Vector3.prototype.normalizeToRef = function (reference) {
  3171. var len = this.length();
  3172. if (len === 0 || len === 1.0) {
  3173. reference.set(this.x, this.y, this.z);
  3174. return reference;
  3175. }
  3176. var scale = 1.0 / len;
  3177. this.scaleToRef(scale, reference);
  3178. return reference;
  3179. };
  3180. /**
  3181. * Creates a new Vector3 copied from the current Vector3
  3182. * @returns the new Vector3
  3183. */
  3184. Vector3.prototype.clone = function () {
  3185. return new Vector3(this.x, this.y, this.z);
  3186. };
  3187. /**
  3188. * Copies the given vector coordinates to the current Vector3 ones
  3189. * @param source defines the source Vector3
  3190. * @returns the current updated Vector3
  3191. */
  3192. Vector3.prototype.copyFrom = function (source) {
  3193. this.x = source.x;
  3194. this.y = source.y;
  3195. this.z = source.z;
  3196. return this;
  3197. };
  3198. /**
  3199. * Copies the given floats to the current Vector3 coordinates
  3200. * @param x defines the x coordinate of the operand
  3201. * @param y defines the y coordinate of the operand
  3202. * @param z defines the z coordinate of the operand
  3203. * @returns the current updated Vector3
  3204. */
  3205. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3206. this.x = x;
  3207. this.y = y;
  3208. this.z = z;
  3209. return this;
  3210. };
  3211. /**
  3212. * Copies the given floats to the current Vector3 coordinates
  3213. * @param x defines the x coordinate of the operand
  3214. * @param y defines the y coordinate of the operand
  3215. * @param z defines the z coordinate of the operand
  3216. * @returns the current updated Vector3
  3217. */
  3218. Vector3.prototype.set = function (x, y, z) {
  3219. return this.copyFromFloats(x, y, z);
  3220. };
  3221. // Statics
  3222. /**
  3223. * Get the clip factor between two vectors
  3224. * @param vector0 defines the first operand
  3225. * @param vector1 defines the second operand
  3226. * @param axis defines the axis to use
  3227. * @param size defines the size along the axis
  3228. * @returns the clip factor
  3229. */
  3230. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3231. var d0 = Vector3.Dot(vector0, axis) - size;
  3232. var d1 = Vector3.Dot(vector1, axis) - size;
  3233. var s = d0 / (d0 - d1);
  3234. return s;
  3235. };
  3236. /**
  3237. * Get angle between two vectors
  3238. * @param vector0 angle between vector0 and vector1
  3239. * @param vector1 angle between vector0 and vector1
  3240. * @param normal direction of the normal
  3241. * @return the angle between vector0 and vector1
  3242. */
  3243. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3244. var v0 = vector0.clone().normalize();
  3245. var v1 = vector1.clone().normalize();
  3246. var dot = Vector3.Dot(v0, v1);
  3247. var n = Vector3.Cross(v0, v1);
  3248. if (Vector3.Dot(n, normal) > 0) {
  3249. return Math.acos(dot);
  3250. }
  3251. return -Math.acos(dot);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 set from the index "offset" of the given array
  3255. * @param array defines the source array
  3256. * @param offset defines the offset in the source array
  3257. * @returns the new Vector3
  3258. */
  3259. Vector3.FromArray = function (array, offset) {
  3260. if (!offset) {
  3261. offset = 0;
  3262. }
  3263. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3267. * This function is deprecated. Use FromArray instead
  3268. * @param array defines the source array
  3269. * @param offset defines the offset in the source array
  3270. * @returns the new Vector3
  3271. */
  3272. Vector3.FromFloatArray = function (array, offset) {
  3273. return Vector3.FromArray(array, offset);
  3274. };
  3275. /**
  3276. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.FromArrayToRef = function (array, offset, result) {
  3282. result.x = array[offset];
  3283. result.y = array[offset + 1];
  3284. result.z = array[offset + 2];
  3285. };
  3286. /**
  3287. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3288. * This function is deprecated. Use FromArrayToRef instead.
  3289. * @param array defines the source array
  3290. * @param offset defines the offset in the source array
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3294. return Vector3.FromArrayToRef(array, offset, result);
  3295. };
  3296. /**
  3297. * Sets the given vector "result" with the given floats.
  3298. * @param x defines the x coordinate of the source
  3299. * @param y defines the y coordinate of the source
  3300. * @param z defines the z coordinate of the source
  3301. * @param result defines the Vector3 where to store the result
  3302. */
  3303. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3304. result.x = x;
  3305. result.y = y;
  3306. result.z = z;
  3307. };
  3308. /**
  3309. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3310. * @returns a new empty Vector3
  3311. */
  3312. Vector3.Zero = function () {
  3313. return new Vector3(0.0, 0.0, 0.0);
  3314. };
  3315. /**
  3316. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3317. * @returns a new unit Vector3
  3318. */
  3319. Vector3.One = function () {
  3320. return new Vector3(1.0, 1.0, 1.0);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3324. * @returns a new up Vector3
  3325. */
  3326. Vector3.Up = function () {
  3327. return new Vector3(0.0, 1.0, 0.0);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3331. * @returns a new forward Vector3
  3332. */
  3333. Vector3.Forward = function () {
  3334. return new Vector3(0.0, 0.0, 1.0);
  3335. };
  3336. /**
  3337. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3338. * @returns a new right Vector3
  3339. */
  3340. Vector3.Right = function () {
  3341. return new Vector3(1.0, 0.0, 0.0);
  3342. };
  3343. /**
  3344. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3345. * @returns a new left Vector3
  3346. */
  3347. Vector3.Left = function () {
  3348. return new Vector3(-1.0, 0.0, 0.0);
  3349. };
  3350. /**
  3351. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3352. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3353. * @param vector defines the Vector3 to transform
  3354. * @param transformation defines the transformation matrix
  3355. * @returns the transformed Vector3
  3356. */
  3357. Vector3.TransformCoordinates = function (vector, transformation) {
  3358. var result = Vector3.Zero();
  3359. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3364. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3365. * @param vector defines the Vector3 to transform
  3366. * @param transformation defines the transformation matrix
  3367. * @param result defines the Vector3 where to store the result
  3368. */
  3369. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3370. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3371. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3372. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3373. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3374. result.x = x / w;
  3375. result.y = y / w;
  3376. result.z = z / w;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3380. * This method computes tranformed coordinates only, not transformed direction vectors
  3381. * @param x define the x coordinate of the source vector
  3382. * @param y define the y coordinate of the source vector
  3383. * @param z define the z coordinate of the source vector
  3384. * @param transformation defines the transformation matrix
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3388. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3389. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3390. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3391. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3392. result.x = rx / rw;
  3393. result.y = ry / rw;
  3394. result.z = rz / rw;
  3395. };
  3396. /**
  3397. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param vector defines the Vector3 to transform
  3400. * @param transformation defines the transformation matrix
  3401. * @returns the new Vector3
  3402. */
  3403. Vector3.TransformNormal = function (vector, transformation) {
  3404. var result = Vector3.Zero();
  3405. Vector3.TransformNormalToRef(vector, transformation, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3410. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3411. * @param vector defines the Vector3 to transform
  3412. * @param transformation defines the transformation matrix
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3416. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3417. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3418. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3419. result.x = x;
  3420. result.y = y;
  3421. result.z = z;
  3422. };
  3423. /**
  3424. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3425. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3426. * @param x define the x coordinate of the source vector
  3427. * @param y define the y coordinate of the source vector
  3428. * @param z define the z coordinate of the source vector
  3429. * @param transformation defines the transformation matrix
  3430. * @param result defines the Vector3 where to store the result
  3431. */
  3432. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3433. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3434. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3435. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3436. };
  3437. /**
  3438. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3439. * @param value1 defines the first control point
  3440. * @param value2 defines the second control point
  3441. * @param value3 defines the third control point
  3442. * @param value4 defines the fourth control point
  3443. * @param amount defines the amount on the spline to use
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3447. var squared = amount * amount;
  3448. var cubed = amount * squared;
  3449. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3450. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3451. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3452. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3453. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3454. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3455. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3456. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3457. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3458. return new Vector3(x, y, z);
  3459. };
  3460. /**
  3461. * 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"
  3462. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3463. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3464. * @param value defines the current value
  3465. * @param min defines the lower range value
  3466. * @param max defines the upper range value
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.Clamp = function (value, min, max) {
  3470. var x = value.x;
  3471. x = (x > max.x) ? max.x : x;
  3472. x = (x < min.x) ? min.x : x;
  3473. var y = value.y;
  3474. y = (y > max.y) ? max.y : y;
  3475. y = (y < min.y) ? min.y : y;
  3476. var z = value.z;
  3477. z = (z > max.z) ? max.z : z;
  3478. z = (z < min.z) ? min.z : z;
  3479. return new Vector3(x, y, z);
  3480. };
  3481. /**
  3482. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3483. * @param value1 defines the first control point
  3484. * @param tangent1 defines the first tangent vector
  3485. * @param value2 defines the second control point
  3486. * @param tangent2 defines the second tangent vector
  3487. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3488. * @returns the new Vector3
  3489. */
  3490. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3491. var squared = amount * amount;
  3492. var cubed = amount * squared;
  3493. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3494. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3495. var part3 = (cubed - (2.0 * squared)) + amount;
  3496. var part4 = cubed - squared;
  3497. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3498. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3499. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3500. return new Vector3(x, y, z);
  3501. };
  3502. /**
  3503. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3504. * @param start defines the start value
  3505. * @param end defines the end value
  3506. * @param amount max defines amount between both (between 0 and 1)
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Lerp = function (start, end, amount) {
  3510. var result = new Vector3(0, 0, 0);
  3511. Vector3.LerpToRef(start, end, amount, result);
  3512. return result;
  3513. };
  3514. /**
  3515. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3516. * @param start defines the start value
  3517. * @param end defines the end value
  3518. * @param amount max defines amount between both (between 0 and 1)
  3519. * @param result defines the Vector3 where to store the result
  3520. */
  3521. Vector3.LerpToRef = function (start, end, amount, result) {
  3522. result.x = start.x + ((end.x - start.x) * amount);
  3523. result.y = start.y + ((end.y - start.y) * amount);
  3524. result.z = start.z + ((end.z - start.z) * amount);
  3525. };
  3526. /**
  3527. * Returns the dot product (float) between the vectors "left" and "right"
  3528. * @param left defines the left operand
  3529. * @param right defines the right operand
  3530. * @returns the dot product
  3531. */
  3532. Vector3.Dot = function (left, right) {
  3533. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3537. * The cross product is then orthogonal to both "left" and "right"
  3538. * @param left defines the left operand
  3539. * @param right defines the right operand
  3540. * @returns the cross product
  3541. */
  3542. Vector3.Cross = function (left, right) {
  3543. var result = Vector3.Zero();
  3544. Vector3.CrossToRef(left, right, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the cross product of "left" and "right"
  3549. * The cross product is then orthogonal to both "left" and "right"
  3550. * @param left defines the left operand
  3551. * @param right defines the right operand
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.CrossToRef = function (left, right, result) {
  3555. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3556. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3557. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3558. result.copyFrom(MathTmp.Vector3[0]);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 as the normalization of the given vector
  3562. * @param vector defines the Vector3 to normalize
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.Normalize = function (vector) {
  3566. var result = Vector3.Zero();
  3567. Vector3.NormalizeToRef(vector, result);
  3568. return result;
  3569. };
  3570. /**
  3571. * Sets the given vector "result" with the normalization of the given first vector
  3572. * @param vector defines the Vector3 to normalize
  3573. * @param result defines the Vector3 where to store the result
  3574. */
  3575. Vector3.NormalizeToRef = function (vector, result) {
  3576. result.copyFrom(vector);
  3577. result.normalize();
  3578. };
  3579. /**
  3580. * Project a Vector3 onto screen space
  3581. * @param vector defines the Vector3 to project
  3582. * @param world defines the world matrix to use
  3583. * @param transform defines the transform (view x projection) matrix to use
  3584. * @param viewport defines the screen viewport to use
  3585. * @returns the new Vector3
  3586. */
  3587. Vector3.Project = function (vector, world, transform, viewport) {
  3588. var cw = viewport.width;
  3589. var ch = viewport.height;
  3590. var cx = viewport.x;
  3591. var cy = viewport.y;
  3592. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3593. 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);
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(transform, matrix);
  3596. matrix.multiplyToRef(viewportMatrix, matrix);
  3597. return Vector3.TransformCoordinates(vector, matrix);
  3598. };
  3599. /**
  3600. * Unproject from screen space to object space
  3601. * @param source defines the screen space Vector3 to use
  3602. * @param viewportWidth defines the current width of the viewport
  3603. * @param viewportHeight defines the current height of the viewport
  3604. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3605. * @param transform defines the transform (view x projection) matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3609. var matrix = MathTmp.Matrix[0];
  3610. world.multiplyToRef(transform, matrix);
  3611. matrix.invert();
  3612. source.x = source.x / viewportWidth * 2 - 1;
  3613. source.y = -(source.y / viewportHeight * 2 - 1);
  3614. var vector = Vector3.TransformCoordinates(source, matrix);
  3615. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3616. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3617. vector = vector.scale(1.0 / num);
  3618. }
  3619. return vector;
  3620. };
  3621. /**
  3622. * Unproject from screen space to object space
  3623. * @param source defines the screen space Vector3 to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @returns the new Vector3
  3630. */
  3631. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3632. var result = Vector3.Zero();
  3633. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3634. return result;
  3635. };
  3636. /**
  3637. * Unproject from screen space to object space
  3638. * @param source defines the screen space Vector3 to use
  3639. * @param viewportWidth defines the current width of the viewport
  3640. * @param viewportHeight defines the current height of the viewport
  3641. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3642. * @param view defines the view matrix to use
  3643. * @param projection defines the projection matrix to use
  3644. * @param result defines the Vector3 where to store the result
  3645. */
  3646. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3647. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3648. };
  3649. /**
  3650. * Unproject from screen space to object space
  3651. * @param sourceX defines the screen space x coordinate to use
  3652. * @param sourceY defines the screen space y coordinate to use
  3653. * @param sourceZ defines the screen space z coordinate to use
  3654. * @param viewportWidth defines the current width of the viewport
  3655. * @param viewportHeight defines the current height of the viewport
  3656. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3657. * @param view defines the view matrix to use
  3658. * @param projection defines the projection matrix to use
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3662. var matrix = MathTmp.Matrix[0];
  3663. world.multiplyToRef(view, matrix);
  3664. matrix.multiplyToRef(projection, matrix);
  3665. matrix.invert();
  3666. var screenSource = MathTmp.Vector3[0];
  3667. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3668. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3669. screenSource.z = 2 * sourceZ - 1.0;
  3670. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3671. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3672. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3673. result.scaleInPlace(1.0 / num);
  3674. }
  3675. };
  3676. /**
  3677. * Gets the minimal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Minimize = function (left, right) {
  3683. var min = left.clone();
  3684. min.minimizeInPlace(right);
  3685. return min;
  3686. };
  3687. /**
  3688. * Gets the maximal coordinate values between two Vector3
  3689. * @param left defines the first operand
  3690. * @param right defines the second operand
  3691. * @returns the new Vector3
  3692. */
  3693. Vector3.Maximize = function (left, right) {
  3694. var max = left.clone();
  3695. max.maximizeInPlace(right);
  3696. return max;
  3697. };
  3698. /**
  3699. * Returns the distance between the vectors "value1" and "value2"
  3700. * @param value1 defines the first operand
  3701. * @param value2 defines the second operand
  3702. * @returns the distance
  3703. */
  3704. Vector3.Distance = function (value1, value2) {
  3705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3706. };
  3707. /**
  3708. * Returns the squared distance between the vectors "value1" and "value2"
  3709. * @param value1 defines the first operand
  3710. * @param value2 defines the second operand
  3711. * @returns the squared distance
  3712. */
  3713. Vector3.DistanceSquared = function (value1, value2) {
  3714. var x = value1.x - value2.x;
  3715. var y = value1.y - value2.y;
  3716. var z = value1.z - value2.z;
  3717. return (x * x) + (y * y) + (z * z);
  3718. };
  3719. /**
  3720. * Returns a new Vector3 located at the center between "value1" and "value2"
  3721. * @param value1 defines the first operand
  3722. * @param value2 defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Center = function (value1, value2) {
  3726. var center = value1.add(value2);
  3727. center.scaleInPlace(0.5);
  3728. return center;
  3729. };
  3730. /**
  3731. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3732. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3733. * to something in order to rotate it from its local system to the given target system
  3734. * Note: axis1, axis2 and axis3 are normalized during this operation
  3735. * @param axis1 defines the first axis
  3736. * @param axis2 defines the second axis
  3737. * @param axis3 defines the third axis
  3738. * @returns a new Vector3
  3739. */
  3740. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3741. var rotation = Vector3.Zero();
  3742. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3743. return rotation;
  3744. };
  3745. /**
  3746. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3747. * @param axis1 defines the first axis
  3748. * @param axis2 defines the second axis
  3749. * @param axis3 defines the third axis
  3750. * @param ref defines the Vector3 where to store the result
  3751. */
  3752. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3753. var quat = MathTmp.Quaternion[0];
  3754. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3755. quat.toEulerAnglesToRef(ref);
  3756. };
  3757. return Vector3;
  3758. }());
  3759. BABYLON.Vector3 = Vector3;
  3760. //Vector4 class created for EulerAngle class conversion to Quaternion
  3761. var Vector4 = /** @class */ (function () {
  3762. /**
  3763. * Creates a Vector4 object from the given floats.
  3764. */
  3765. function Vector4(x, y, z, w) {
  3766. this.x = x;
  3767. this.y = y;
  3768. this.z = z;
  3769. this.w = w;
  3770. }
  3771. /**
  3772. * Returns the string with the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.toString = function () {
  3775. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3776. };
  3777. /**
  3778. * Returns the string "Vector4".
  3779. */
  3780. Vector4.prototype.getClassName = function () {
  3781. return "Vector4";
  3782. };
  3783. /**
  3784. * Returns the Vector4 hash code.
  3785. */
  3786. Vector4.prototype.getHashCode = function () {
  3787. var hash = this.x || 0;
  3788. hash = (hash * 397) ^ (this.y || 0);
  3789. hash = (hash * 397) ^ (this.z || 0);
  3790. hash = (hash * 397) ^ (this.w || 0);
  3791. return hash;
  3792. };
  3793. // Operators
  3794. /**
  3795. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3796. */
  3797. Vector4.prototype.asArray = function () {
  3798. var result = new Array();
  3799. this.toArray(result, 0);
  3800. return result;
  3801. };
  3802. /**
  3803. * Populates the given array from the given index with the Vector4 coordinates.
  3804. * Returns the Vector4.
  3805. */
  3806. Vector4.prototype.toArray = function (array, index) {
  3807. if (index === undefined) {
  3808. index = 0;
  3809. }
  3810. array[index] = this.x;
  3811. array[index + 1] = this.y;
  3812. array[index + 2] = this.z;
  3813. array[index + 3] = this.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Adds the given vector to the current Vector4.
  3818. * Returns the updated Vector4.
  3819. */
  3820. Vector4.prototype.addInPlace = function (otherVector) {
  3821. this.x += otherVector.x;
  3822. this.y += otherVector.y;
  3823. this.z += otherVector.z;
  3824. this.w += otherVector.w;
  3825. return this;
  3826. };
  3827. /**
  3828. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3829. */
  3830. Vector4.prototype.add = function (otherVector) {
  3831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3832. };
  3833. /**
  3834. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3835. * Returns the current Vector4.
  3836. */
  3837. Vector4.prototype.addToRef = function (otherVector, result) {
  3838. result.x = this.x + otherVector.x;
  3839. result.y = this.y + otherVector.y;
  3840. result.z = this.z + otherVector.z;
  3841. result.w = this.w + otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Subtract in place the given vector from the current Vector4.
  3846. * Returns the updated Vector4.
  3847. */
  3848. Vector4.prototype.subtractInPlace = function (otherVector) {
  3849. this.x -= otherVector.x;
  3850. this.y -= otherVector.y;
  3851. this.z -= otherVector.z;
  3852. this.w -= otherVector.w;
  3853. return this;
  3854. };
  3855. /**
  3856. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3857. */
  3858. Vector4.prototype.subtract = function (otherVector) {
  3859. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3860. };
  3861. /**
  3862. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3863. * Returns the current Vector4.
  3864. */
  3865. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3866. result.x = this.x - otherVector.x;
  3867. result.y = this.y - otherVector.y;
  3868. result.z = this.z - otherVector.z;
  3869. result.w = this.w - otherVector.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3876. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3877. };
  3878. /**
  3879. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3880. * Returns the current Vector4.
  3881. */
  3882. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3883. result.x = this.x - x;
  3884. result.y = this.y - y;
  3885. result.z = this.z - z;
  3886. result.w = this.w - w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3891. */
  3892. Vector4.prototype.negate = function () {
  3893. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3894. };
  3895. /**
  3896. * Multiplies the current Vector4 coordinates by scale (float).
  3897. * Returns the updated Vector4.
  3898. */
  3899. Vector4.prototype.scaleInPlace = function (scale) {
  3900. this.x *= scale;
  3901. this.y *= scale;
  3902. this.z *= scale;
  3903. this.w *= scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3908. */
  3909. Vector4.prototype.scale = function (scale) {
  3910. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3911. };
  3912. /**
  3913. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3914. * Returns the current Vector4.
  3915. */
  3916. Vector4.prototype.scaleToRef = function (scale, result) {
  3917. result.x = this.x * scale;
  3918. result.y = this.y * scale;
  3919. result.z = this.z * scale;
  3920. result.w = this.w * scale;
  3921. return this;
  3922. };
  3923. /**
  3924. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3925. * @param scale defines the scale factor
  3926. * @param result defines the Vector4 object where to store the result
  3927. * @returns the unmodified current Vector4
  3928. */
  3929. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3930. result.x += this.x * scale;
  3931. result.y += this.y * scale;
  3932. result.z += this.z * scale;
  3933. result.w += this.w * scale;
  3934. return this;
  3935. };
  3936. /**
  3937. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3938. */
  3939. Vector4.prototype.equals = function (otherVector) {
  3940. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3941. };
  3942. /**
  3943. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3944. */
  3945. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3946. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3947. return otherVector
  3948. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3949. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3950. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3951. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3952. };
  3953. /**
  3954. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3955. */
  3956. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3957. return this.x === x && this.y === y && this.z === z && this.w === w;
  3958. };
  3959. /**
  3960. * Multiplies in place the current Vector4 by the given one.
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3964. this.x *= otherVector.x;
  3965. this.y *= otherVector.y;
  3966. this.z *= otherVector.z;
  3967. this.w *= otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3972. */
  3973. Vector4.prototype.multiply = function (otherVector) {
  3974. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3981. result.x = this.x * otherVector.x;
  3982. result.y = this.y * otherVector.y;
  3983. result.z = this.z * otherVector.z;
  3984. result.w = this.w * otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3989. */
  3990. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3991. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3992. };
  3993. /**
  3994. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3995. */
  3996. Vector4.prototype.divide = function (otherVector) {
  3997. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3998. };
  3999. /**
  4000. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4001. * Returns the current Vector4.
  4002. */
  4003. Vector4.prototype.divideToRef = function (otherVector, result) {
  4004. result.x = this.x / otherVector.x;
  4005. result.y = this.y / otherVector.y;
  4006. result.z = this.z / otherVector.z;
  4007. result.w = this.w / otherVector.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Divides the current Vector3 coordinates by the given ones.
  4012. * @returns the updated Vector3.
  4013. */
  4014. Vector4.prototype.divideInPlace = function (otherVector) {
  4015. return this.divideToRef(otherVector, this);
  4016. };
  4017. /**
  4018. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4019. * @param other defines the second operand
  4020. * @returns the current updated Vector4
  4021. */
  4022. Vector4.prototype.minimizeInPlace = function (other) {
  4023. if (other.x < this.x)
  4024. this.x = other.x;
  4025. if (other.y < this.y)
  4026. this.y = other.y;
  4027. if (other.z < this.z)
  4028. this.z = other.z;
  4029. if (other.w < this.w)
  4030. this.w = other.w;
  4031. return this;
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.maximizeInPlace = function (other) {
  4039. if (other.x > this.x)
  4040. this.x = other.x;
  4041. if (other.y > this.y)
  4042. this.y = other.y;
  4043. if (other.z > this.z)
  4044. this.z = other.z;
  4045. if (other.w > this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. // Properties
  4050. /**
  4051. * Returns the Vector4 length (float).
  4052. */
  4053. Vector4.prototype.length = function () {
  4054. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4055. };
  4056. /**
  4057. * Returns the Vector4 squared length (float).
  4058. */
  4059. Vector4.prototype.lengthSquared = function () {
  4060. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4061. };
  4062. // Methods
  4063. /**
  4064. * Normalizes in place the Vector4.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.normalize = function () {
  4068. var len = this.length();
  4069. if (len === 0)
  4070. return this;
  4071. var num = 1.0 / len;
  4072. this.x *= num;
  4073. this.y *= num;
  4074. this.z *= num;
  4075. this.w *= num;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4080. */
  4081. Vector4.prototype.toVector3 = function () {
  4082. return new Vector3(this.x, this.y, this.z);
  4083. };
  4084. /**
  4085. * Returns a new Vector4 copied from the current one.
  4086. */
  4087. Vector4.prototype.clone = function () {
  4088. return new Vector4(this.x, this.y, this.z, this.w);
  4089. };
  4090. /**
  4091. * Updates the current Vector4 with the given one coordinates.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFrom = function (source) {
  4095. this.x = source.x;
  4096. this.y = source.y;
  4097. this.z = source.z;
  4098. this.w = source.w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4106. this.x = x;
  4107. this.y = y;
  4108. this.z = z;
  4109. this.w = w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the current Vector4 coordinates with the given floats.
  4114. * Returns the updated Vector4.
  4115. */
  4116. Vector4.prototype.set = function (x, y, z, w) {
  4117. return this.copyFromFloats(x, y, z, w);
  4118. };
  4119. // Statics
  4120. /**
  4121. * Returns a new Vector4 set from the starting index of the given array.
  4122. */
  4123. Vector4.FromArray = function (array, offset) {
  4124. if (!offset) {
  4125. offset = 0;
  4126. }
  4127. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4128. };
  4129. /**
  4130. * Updates the given vector "result" from the starting index of the given array.
  4131. */
  4132. Vector4.FromArrayToRef = function (array, offset, result) {
  4133. result.x = array[offset];
  4134. result.y = array[offset + 1];
  4135. result.z = array[offset + 2];
  4136. result.w = array[offset + 3];
  4137. };
  4138. /**
  4139. * Updates the given vector "result" from the starting index of the given Float32Array.
  4140. */
  4141. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4142. Vector4.FromArrayToRef(array, offset, result);
  4143. };
  4144. /**
  4145. * Updates the given vector "result" coordinates from the given floats.
  4146. */
  4147. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4148. result.x = x;
  4149. result.y = y;
  4150. result.z = z;
  4151. result.w = w;
  4152. };
  4153. /**
  4154. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4155. */
  4156. Vector4.Zero = function () {
  4157. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4158. };
  4159. /**
  4160. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4161. */
  4162. Vector4.One = function () {
  4163. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4164. };
  4165. /**
  4166. * Returns a new normalized Vector4 from the given one.
  4167. */
  4168. Vector4.Normalize = function (vector) {
  4169. var result = Vector4.Zero();
  4170. Vector4.NormalizeToRef(vector, result);
  4171. return result;
  4172. };
  4173. /**
  4174. * Updates the given vector "result" from the normalization of the given one.
  4175. */
  4176. Vector4.NormalizeToRef = function (vector, result) {
  4177. result.copyFrom(vector);
  4178. result.normalize();
  4179. };
  4180. Vector4.Minimize = function (left, right) {
  4181. var min = left.clone();
  4182. min.minimizeInPlace(right);
  4183. return min;
  4184. };
  4185. Vector4.Maximize = function (left, right) {
  4186. var max = left.clone();
  4187. max.maximizeInPlace(right);
  4188. return max;
  4189. };
  4190. /**
  4191. * Returns the distance (float) between the vectors "value1" and "value2".
  4192. */
  4193. Vector4.Distance = function (value1, value2) {
  4194. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4195. };
  4196. /**
  4197. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4198. */
  4199. Vector4.DistanceSquared = function (value1, value2) {
  4200. var x = value1.x - value2.x;
  4201. var y = value1.y - value2.y;
  4202. var z = value1.z - value2.z;
  4203. var w = value1.w - value2.w;
  4204. return (x * x) + (y * y) + (z * z) + (w * w);
  4205. };
  4206. /**
  4207. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Center = function (value1, value2) {
  4210. var center = value1.add(value2);
  4211. center.scaleInPlace(0.5);
  4212. return center;
  4213. };
  4214. /**
  4215. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4216. * This methods computes transformed normalized direction vectors only.
  4217. */
  4218. Vector4.TransformNormal = function (vector, transformation) {
  4219. var result = Vector4.Zero();
  4220. Vector4.TransformNormalToRef(vector, transformation, result);
  4221. return result;
  4222. };
  4223. /**
  4224. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4225. * This methods computes transformed normalized direction vectors only.
  4226. */
  4227. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4228. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4229. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4230. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4231. result.x = x;
  4232. result.y = y;
  4233. result.z = z;
  4234. result.w = vector.w;
  4235. };
  4236. /**
  4237. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4238. * This methods computes transformed normalized direction vectors only.
  4239. */
  4240. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4241. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4242. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4243. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4244. result.w = w;
  4245. };
  4246. return Vector4;
  4247. }());
  4248. BABYLON.Vector4 = Vector4;
  4249. var Size = /** @class */ (function () {
  4250. /**
  4251. * Creates a Size object from the given width and height (floats).
  4252. */
  4253. function Size(width, height) {
  4254. this.width = width;
  4255. this.height = height;
  4256. }
  4257. // Returns a string with the Size width and height.
  4258. Size.prototype.toString = function () {
  4259. return "{W: " + this.width + ", H: " + this.height + "}";
  4260. };
  4261. /**
  4262. * Returns the string "Size"
  4263. */
  4264. Size.prototype.getClassName = function () {
  4265. return "Size";
  4266. };
  4267. /**
  4268. * Returns the Size hash code.
  4269. */
  4270. Size.prototype.getHashCode = function () {
  4271. var hash = this.width || 0;
  4272. hash = (hash * 397) ^ (this.height || 0);
  4273. return hash;
  4274. };
  4275. /**
  4276. * Updates the current size from the given one.
  4277. * Returns the updated Size.
  4278. */
  4279. Size.prototype.copyFrom = function (src) {
  4280. this.width = src.width;
  4281. this.height = src.height;
  4282. };
  4283. /**
  4284. * Updates in place the current Size from the given floats.
  4285. * Returns the updated Size.
  4286. */
  4287. Size.prototype.copyFromFloats = function (width, height) {
  4288. this.width = width;
  4289. this.height = height;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates in place the current Size from the given floats.
  4294. * Returns the updated Size.
  4295. */
  4296. Size.prototype.set = function (width, height) {
  4297. return this.copyFromFloats(width, height);
  4298. };
  4299. /**
  4300. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4301. */
  4302. Size.prototype.multiplyByFloats = function (w, h) {
  4303. return new Size(this.width * w, this.height * h);
  4304. };
  4305. /**
  4306. * Returns a new Size copied from the given one.
  4307. */
  4308. Size.prototype.clone = function () {
  4309. return new Size(this.width, this.height);
  4310. };
  4311. /**
  4312. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4313. */
  4314. Size.prototype.equals = function (other) {
  4315. if (!other) {
  4316. return false;
  4317. }
  4318. return (this.width === other.width) && (this.height === other.height);
  4319. };
  4320. Object.defineProperty(Size.prototype, "surface", {
  4321. /**
  4322. * Returns the surface of the Size : width * height (float).
  4323. */
  4324. get: function () {
  4325. return this.width * this.height;
  4326. },
  4327. enumerable: true,
  4328. configurable: true
  4329. });
  4330. /**
  4331. * Returns a new Size set to (0.0, 0.0)
  4332. */
  4333. Size.Zero = function () {
  4334. return new Size(0.0, 0.0);
  4335. };
  4336. /**
  4337. * Returns a new Size set as the addition result of the current Size and the given one.
  4338. */
  4339. Size.prototype.add = function (otherSize) {
  4340. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4341. return r;
  4342. };
  4343. /**
  4344. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4345. */
  4346. Size.prototype.subtract = function (otherSize) {
  4347. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4348. return r;
  4349. };
  4350. /**
  4351. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4352. */
  4353. Size.Lerp = function (start, end, amount) {
  4354. var w = start.width + ((end.width - start.width) * amount);
  4355. var h = start.height + ((end.height - start.height) * amount);
  4356. return new Size(w, h);
  4357. };
  4358. return Size;
  4359. }());
  4360. BABYLON.Size = Size;
  4361. /**
  4362. * Class used to store quaternion data
  4363. * @see https://en.wikipedia.org/wiki/Quaternion
  4364. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4365. */
  4366. var Quaternion = /** @class */ (function () {
  4367. /**
  4368. * Creates a new Quaternion from the given floats
  4369. * @param x defines the first component (0 by default)
  4370. * @param y defines the second component (0 by default)
  4371. * @param z defines the third component (0 by default)
  4372. * @param w defines the fourth component (1.0 by default)
  4373. */
  4374. function Quaternion(
  4375. /** defines the first component (0 by default) */
  4376. x,
  4377. /** defines the second component (0 by default) */
  4378. y,
  4379. /** defines the third component (0 by default) */
  4380. z,
  4381. /** defines the fourth component (1.0 by default) */
  4382. w) {
  4383. if (x === void 0) { x = 0.0; }
  4384. if (y === void 0) { y = 0.0; }
  4385. if (z === void 0) { z = 0.0; }
  4386. if (w === void 0) { w = 1.0; }
  4387. this.x = x;
  4388. this.y = y;
  4389. this.z = z;
  4390. this.w = w;
  4391. }
  4392. /**
  4393. * Gets a string representation for the current quaternion
  4394. * @returns a string with the Quaternion coordinates
  4395. */
  4396. Quaternion.prototype.toString = function () {
  4397. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4398. };
  4399. /**
  4400. * Gets the class name of the quaternion
  4401. * @returns the string "Quaternion"
  4402. */
  4403. Quaternion.prototype.getClassName = function () {
  4404. return "Quaternion";
  4405. };
  4406. /**
  4407. * Gets a hash code for this quaternion
  4408. * @returns the quaternion hash code
  4409. */
  4410. Quaternion.prototype.getHashCode = function () {
  4411. var hash = this.x || 0;
  4412. hash = (hash * 397) ^ (this.y || 0);
  4413. hash = (hash * 397) ^ (this.z || 0);
  4414. hash = (hash * 397) ^ (this.w || 0);
  4415. return hash;
  4416. };
  4417. /**
  4418. * Copy the quaternion to an array
  4419. * @returns a new array populated with 4 elements from the quaternion coordinates
  4420. */
  4421. Quaternion.prototype.asArray = function () {
  4422. return [this.x, this.y, this.z, this.w];
  4423. };
  4424. /**
  4425. * Check if two quaternions are equals
  4426. * @param otherQuaternion defines the second operand
  4427. * @return true if the current quaternion and the given one coordinates are strictly equals
  4428. */
  4429. Quaternion.prototype.equals = function (otherQuaternion) {
  4430. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4431. };
  4432. /**
  4433. * Clone the current quaternion
  4434. * @returns a new quaternion copied from the current one
  4435. */
  4436. Quaternion.prototype.clone = function () {
  4437. return new Quaternion(this.x, this.y, this.z, this.w);
  4438. };
  4439. /**
  4440. * Copy a quaternion to the current one
  4441. * @param other defines the other quaternion
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.copyFrom = function (other) {
  4445. this.x = other.x;
  4446. this.y = other.y;
  4447. this.z = other.z;
  4448. this.w = other.w;
  4449. return this;
  4450. };
  4451. /**
  4452. * Updates the current quaternion with the given float coordinates
  4453. * @param x defines the x coordinate
  4454. * @param y defines the y coordinate
  4455. * @param z defines the z coordinate
  4456. * @param w defines the w coordinate
  4457. * @returns the updated current quaternion
  4458. */
  4459. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4460. this.x = x;
  4461. this.y = y;
  4462. this.z = z;
  4463. this.w = w;
  4464. return this;
  4465. };
  4466. /**
  4467. * Updates the current quaternion from the given float coordinates
  4468. * @param x defines the x coordinate
  4469. * @param y defines the y coordinate
  4470. * @param z defines the z coordinate
  4471. * @param w defines the w coordinate
  4472. * @returns the updated current quaternion
  4473. */
  4474. Quaternion.prototype.set = function (x, y, z, w) {
  4475. return this.copyFromFloats(x, y, z, w);
  4476. };
  4477. /**
  4478. * Adds two quaternions
  4479. * @param other defines the second operand
  4480. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4481. */
  4482. Quaternion.prototype.add = function (other) {
  4483. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4484. };
  4485. /**
  4486. * Add a quaternion to the current one
  4487. * @param other defines the quaternion to add
  4488. * @returns the current quaternion
  4489. */
  4490. Quaternion.prototype.addInPlace = function (other) {
  4491. this.x += other.x;
  4492. this.y += other.y;
  4493. this.z += other.z;
  4494. this.w += other.w;
  4495. return this;
  4496. };
  4497. /**
  4498. * Subtract two quaternions
  4499. * @param other defines the second operand
  4500. * @returns a new quaternion as the subtraction result of the given one from the current one
  4501. */
  4502. Quaternion.prototype.subtract = function (other) {
  4503. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4504. };
  4505. /**
  4506. * Multiplies the current quaternion by a scale factor
  4507. * @param value defines the scale factor
  4508. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4509. */
  4510. Quaternion.prototype.scale = function (value) {
  4511. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4512. };
  4513. /**
  4514. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4515. * @param scale defines the scale factor
  4516. * @param result defines the Quaternion object where to store the result
  4517. * @returns the unmodified current quaternion
  4518. */
  4519. Quaternion.prototype.scaleToRef = function (scale, result) {
  4520. result.x = this.x * scale;
  4521. result.y = this.y * scale;
  4522. result.z = this.z * scale;
  4523. result.w = this.w * scale;
  4524. return this;
  4525. };
  4526. /**
  4527. * Multiplies in place the current quaternion by a scale factor
  4528. * @param value defines the scale factor
  4529. * @returns the current modified quaternion
  4530. */
  4531. Quaternion.prototype.scaleInPlace = function (value) {
  4532. this.x *= value;
  4533. this.y *= value;
  4534. this.z *= value;
  4535. this.w *= value;
  4536. return this;
  4537. };
  4538. /**
  4539. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4540. * @param scale defines the scale factor
  4541. * @param result defines the Quaternion object where to store the result
  4542. * @returns the unmodified current quaternion
  4543. */
  4544. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4545. result.x += this.x * scale;
  4546. result.y += this.y * scale;
  4547. result.z += this.z * scale;
  4548. result.w += this.w * scale;
  4549. return this;
  4550. };
  4551. /**
  4552. * Multiplies two quaternions
  4553. * @param q1 defines the second operand
  4554. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4555. */
  4556. Quaternion.prototype.multiply = function (q1) {
  4557. var result = new Quaternion(0, 0, 0, 1.0);
  4558. this.multiplyToRef(q1, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4563. * @param q1 defines the second operand
  4564. * @param result defines the target quaternion
  4565. * @returns the current quaternion
  4566. */
  4567. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4568. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4569. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4570. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4571. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4572. result.copyFromFloats(x, y, z, w);
  4573. return this;
  4574. };
  4575. /**
  4576. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4577. * @param q1 defines the second operand
  4578. * @returns the currentupdated quaternion
  4579. */
  4580. Quaternion.prototype.multiplyInPlace = function (q1) {
  4581. this.multiplyToRef(q1, this);
  4582. return this;
  4583. };
  4584. /**
  4585. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4586. * @param ref defines the target quaternion
  4587. * @returns the current quaternion
  4588. */
  4589. Quaternion.prototype.conjugateToRef = function (ref) {
  4590. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4591. return this;
  4592. };
  4593. /**
  4594. * Conjugates in place (1-q) the current quaternion
  4595. * @returns the current updated quaternion
  4596. */
  4597. Quaternion.prototype.conjugateInPlace = function () {
  4598. this.x *= -1;
  4599. this.y *= -1;
  4600. this.z *= -1;
  4601. return this;
  4602. };
  4603. /**
  4604. * Conjugates in place (1-q) the current quaternion
  4605. * @returns a new quaternion
  4606. */
  4607. Quaternion.prototype.conjugate = function () {
  4608. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4609. return result;
  4610. };
  4611. /**
  4612. * Gets length of current quaternion
  4613. * @returns the quaternion length (float)
  4614. */
  4615. Quaternion.prototype.length = function () {
  4616. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4617. };
  4618. /**
  4619. * Normalize in place the current quaternion
  4620. * @returns the current updated quaternion
  4621. */
  4622. Quaternion.prototype.normalize = function () {
  4623. var length = 1.0 / this.length();
  4624. this.x *= length;
  4625. this.y *= length;
  4626. this.z *= length;
  4627. this.w *= length;
  4628. return this;
  4629. };
  4630. /**
  4631. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4632. * @param order is a reserved parameter and is ignore for now
  4633. * @returns a new Vector3 containing the Euler angles
  4634. */
  4635. Quaternion.prototype.toEulerAngles = function (order) {
  4636. if (order === void 0) { order = "YZX"; }
  4637. var result = Vector3.Zero();
  4638. this.toEulerAnglesToRef(result, order);
  4639. return result;
  4640. };
  4641. /**
  4642. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4643. * @param result defines the vector which will be filled with the Euler angles
  4644. * @param order is a reserved parameter and is ignore for now
  4645. * @returns the current unchanged quaternion
  4646. */
  4647. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4648. if (order === void 0) { order = "YZX"; }
  4649. var qz = this.z;
  4650. var qx = this.x;
  4651. var qy = this.y;
  4652. var qw = this.w;
  4653. var sqw = qw * qw;
  4654. var sqz = qz * qz;
  4655. var sqx = qx * qx;
  4656. var sqy = qy * qy;
  4657. var zAxisY = qy * qz - qx * qw;
  4658. var limit = .4999999;
  4659. if (zAxisY < -limit) {
  4660. result.y = 2 * Math.atan2(qy, qw);
  4661. result.x = Math.PI / 2;
  4662. result.z = 0;
  4663. }
  4664. else if (zAxisY > limit) {
  4665. result.y = 2 * Math.atan2(qy, qw);
  4666. result.x = -Math.PI / 2;
  4667. result.z = 0;
  4668. }
  4669. else {
  4670. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4671. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4672. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4673. }
  4674. return this;
  4675. };
  4676. /**
  4677. * Updates the given rotation matrix with the current quaternion values
  4678. * @param result defines the target matrix
  4679. * @returns the current unchanged quaternion
  4680. */
  4681. Quaternion.prototype.toRotationMatrix = function (result) {
  4682. var xx = this.x * this.x;
  4683. var yy = this.y * this.y;
  4684. var zz = this.z * this.z;
  4685. var xy = this.x * this.y;
  4686. var zw = this.z * this.w;
  4687. var zx = this.z * this.x;
  4688. var yw = this.y * this.w;
  4689. var yz = this.y * this.z;
  4690. var xw = this.x * this.w;
  4691. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4692. result.m[1] = 2.0 * (xy + zw);
  4693. result.m[2] = 2.0 * (zx - yw);
  4694. result.m[3] = 0;
  4695. result.m[4] = 2.0 * (xy - zw);
  4696. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4697. result.m[6] = 2.0 * (yz + xw);
  4698. result.m[7] = 0;
  4699. result.m[8] = 2.0 * (zx + yw);
  4700. result.m[9] = 2.0 * (yz - xw);
  4701. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4702. result.m[11] = 0;
  4703. result.m[12] = 0;
  4704. result.m[13] = 0;
  4705. result.m[14] = 0;
  4706. result.m[15] = 1.0;
  4707. result._markAsUpdated();
  4708. return this;
  4709. };
  4710. /**
  4711. * Updates the current quaternion from the given rotation matrix values
  4712. * @param matrix defines the source matrix
  4713. * @returns the current updated quaternion
  4714. */
  4715. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4716. Quaternion.FromRotationMatrixToRef(matrix, this);
  4717. return this;
  4718. };
  4719. // Statics
  4720. /**
  4721. * Creates a new quaternion from a rotation matrix
  4722. * @param matrix defines the source matrix
  4723. * @returns a new quaternion created from the given rotation matrix values
  4724. */
  4725. Quaternion.FromRotationMatrix = function (matrix) {
  4726. var result = new Quaternion();
  4727. Quaternion.FromRotationMatrixToRef(matrix, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Updates the given quaternion with the given rotation matrix values
  4732. * @param matrix defines the source matrix
  4733. * @param result defines the target quaternion
  4734. */
  4735. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4736. var data = matrix.m;
  4737. var m11 = data[0], m12 = data[4], m13 = data[8];
  4738. var m21 = data[1], m22 = data[5], m23 = data[9];
  4739. var m31 = data[2], m32 = data[6], m33 = data[10];
  4740. var trace = m11 + m22 + m33;
  4741. var s;
  4742. if (trace > 0) {
  4743. s = 0.5 / Math.sqrt(trace + 1.0);
  4744. result.w = 0.25 / s;
  4745. result.x = (m32 - m23) * s;
  4746. result.y = (m13 - m31) * s;
  4747. result.z = (m21 - m12) * s;
  4748. }
  4749. else if (m11 > m22 && m11 > m33) {
  4750. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4751. result.w = (m32 - m23) / s;
  4752. result.x = 0.25 * s;
  4753. result.y = (m12 + m21) / s;
  4754. result.z = (m13 + m31) / s;
  4755. }
  4756. else if (m22 > m33) {
  4757. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4758. result.w = (m13 - m31) / s;
  4759. result.x = (m12 + m21) / s;
  4760. result.y = 0.25 * s;
  4761. result.z = (m23 + m32) / s;
  4762. }
  4763. else {
  4764. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4765. result.w = (m21 - m12) / s;
  4766. result.x = (m13 + m31) / s;
  4767. result.y = (m23 + m32) / s;
  4768. result.z = 0.25 * s;
  4769. }
  4770. };
  4771. /**
  4772. * Returns the dot product (float) between the quaternions "left" and "right"
  4773. * @param left defines the left operand
  4774. * @param right defines the right operand
  4775. * @returns the dot product
  4776. */
  4777. Quaternion.Dot = function (left, right) {
  4778. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4779. };
  4780. /**
  4781. * Checks if the two quaternions are close to each other
  4782. * @param quat0 defines the first quaternion to check
  4783. * @param quat1 defines the second quaternion to check
  4784. * @returns true if the two quaternions are close to each other
  4785. */
  4786. Quaternion.AreClose = function (quat0, quat1) {
  4787. var dot = Quaternion.Dot(quat0, quat1);
  4788. return dot >= 0;
  4789. };
  4790. /**
  4791. * Creates an empty quaternion
  4792. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4793. */
  4794. Quaternion.Zero = function () {
  4795. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4796. };
  4797. /**
  4798. * Inverse a given quaternion
  4799. * @param q defines the source quaternion
  4800. * @returns a new quaternion as the inverted current quaternion
  4801. */
  4802. Quaternion.Inverse = function (q) {
  4803. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4804. };
  4805. /**
  4806. * Creates an identity quaternion
  4807. * @returns the identity quaternion
  4808. */
  4809. Quaternion.Identity = function () {
  4810. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4811. };
  4812. /**
  4813. * Gets a boolean indicating if the given quaternion is identity
  4814. * @param quaternion defines the quaternion to check
  4815. * @returns true if the quaternion is identity
  4816. */
  4817. Quaternion.IsIdentity = function (quaternion) {
  4818. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4819. };
  4820. /**
  4821. * Creates a quaternion from a rotation around an axis
  4822. * @param axis defines the axis to use
  4823. * @param angle defines the angle to use
  4824. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4825. */
  4826. Quaternion.RotationAxis = function (axis, angle) {
  4827. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4828. };
  4829. /**
  4830. * Creates a rotation around an axis and stores it into the given quaternion
  4831. * @param axis defines the axis to use
  4832. * @param angle defines the angle to use
  4833. * @param result defines the target quaternion
  4834. * @returns the target quaternion
  4835. */
  4836. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4837. var sin = Math.sin(angle / 2);
  4838. axis.normalize();
  4839. result.w = Math.cos(angle / 2);
  4840. result.x = axis.x * sin;
  4841. result.y = axis.y * sin;
  4842. result.z = axis.z * sin;
  4843. return result;
  4844. };
  4845. /**
  4846. * Creates a new quaternion from data stored into an array
  4847. * @param array defines the data source
  4848. * @param offset defines the offset in the source array where the data starts
  4849. * @returns a new quaternion
  4850. */
  4851. Quaternion.FromArray = function (array, offset) {
  4852. if (!offset) {
  4853. offset = 0;
  4854. }
  4855. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4856. };
  4857. /**
  4858. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4859. * @param yaw defines the rotation around Y axis
  4860. * @param pitch defines the rotation around X axis
  4861. * @param roll defines the rotation around Z axis
  4862. * @returns the new quaternion
  4863. */
  4864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4865. var q = new Quaternion();
  4866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4867. return q;
  4868. };
  4869. /**
  4870. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4871. * @param yaw defines the rotation around Y axis
  4872. * @param pitch defines the rotation around X axis
  4873. * @param roll defines the rotation around Z axis
  4874. * @param result defines the target quaternion
  4875. */
  4876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4878. var halfRoll = roll * 0.5;
  4879. var halfPitch = pitch * 0.5;
  4880. var halfYaw = yaw * 0.5;
  4881. var sinRoll = Math.sin(halfRoll);
  4882. var cosRoll = Math.cos(halfRoll);
  4883. var sinPitch = Math.sin(halfPitch);
  4884. var cosPitch = Math.cos(halfPitch);
  4885. var sinYaw = Math.sin(halfYaw);
  4886. var cosYaw = Math.cos(halfYaw);
  4887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4891. };
  4892. /**
  4893. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4894. * @param alpha defines the rotation around first axis
  4895. * @param beta defines the rotation around second axis
  4896. * @param gamma defines the rotation around third axis
  4897. * @returns the new quaternion
  4898. */
  4899. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4900. var result = new Quaternion();
  4901. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4902. return result;
  4903. };
  4904. /**
  4905. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4906. * @param alpha defines the rotation around first axis
  4907. * @param beta defines the rotation around second axis
  4908. * @param gamma defines the rotation around third axis
  4909. * @param result defines the target quaternion
  4910. */
  4911. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4912. // Produces a quaternion from Euler angles in the z-x-z orientation
  4913. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4914. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4915. var halfBeta = beta * 0.5;
  4916. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4917. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4918. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4919. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4920. };
  4921. /**
  4922. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4923. * @param axis1 defines the first axis
  4924. * @param axis2 defines the second axis
  4925. * @param axis3 defines the third axis
  4926. * @returns the new quaternion
  4927. */
  4928. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4929. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4930. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4931. return quat;
  4932. };
  4933. /**
  4934. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4935. * @param axis1 defines the first axis
  4936. * @param axis2 defines the second axis
  4937. * @param axis3 defines the third axis
  4938. * @param ref defines the target quaternion
  4939. */
  4940. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4941. var rotMat = MathTmp.Matrix[0];
  4942. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4943. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4944. };
  4945. /**
  4946. * Interpolates between two quaternions
  4947. * @param left defines first quaternion
  4948. * @param right defines second quaternion
  4949. * @param amount defines the gradient to use
  4950. * @returns the new interpolated quaternion
  4951. */
  4952. Quaternion.Slerp = function (left, right, amount) {
  4953. var result = Quaternion.Identity();
  4954. Quaternion.SlerpToRef(left, right, amount, result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Interpolates between two quaternions and stores it into a target quaternion
  4959. * @param left defines first quaternion
  4960. * @param right defines second quaternion
  4961. * @param amount defines the gradient to use
  4962. * @param result defines the target quaternion
  4963. */
  4964. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4965. var num2;
  4966. var num3;
  4967. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4968. var flag = false;
  4969. if (num4 < 0) {
  4970. flag = true;
  4971. num4 = -num4;
  4972. }
  4973. if (num4 > 0.999999) {
  4974. num3 = 1 - amount;
  4975. num2 = flag ? -amount : amount;
  4976. }
  4977. else {
  4978. var num5 = Math.acos(num4);
  4979. var num6 = (1.0 / Math.sin(num5));
  4980. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4981. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4982. }
  4983. result.x = (num3 * left.x) + (num2 * right.x);
  4984. result.y = (num3 * left.y) + (num2 * right.y);
  4985. result.z = (num3 * left.z) + (num2 * right.z);
  4986. result.w = (num3 * left.w) + (num2 * right.w);
  4987. };
  4988. /**
  4989. * Interpolate between two quaternions using Hermite interpolation
  4990. * @param value1 defines first quaternion
  4991. * @param tangent1 defines the incoming tangent
  4992. * @param value2 defines second quaternion
  4993. * @param tangent2 defines the outgoing tangent
  4994. * @param amount defines the target quaternion
  4995. * @returns the new interpolated quaternion
  4996. */
  4997. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4998. var squared = amount * amount;
  4999. var cubed = amount * squared;
  5000. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5001. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5002. var part3 = (cubed - (2.0 * squared)) + amount;
  5003. var part4 = cubed - squared;
  5004. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5005. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5006. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5007. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5008. return new Quaternion(x, y, z, w);
  5009. };
  5010. return Quaternion;
  5011. }());
  5012. BABYLON.Quaternion = Quaternion;
  5013. /**
  5014. * Class used to store matrix data (4x4)
  5015. */
  5016. var Matrix = /** @class */ (function () {
  5017. /**
  5018. * Creates an empty matrix (filled with zeros)
  5019. */
  5020. function Matrix() {
  5021. this._isIdentity = false;
  5022. this._isIdentityDirty = true;
  5023. /**
  5024. * Gets or sets the internal data of the matrix
  5025. */
  5026. this.m = new Float32Array(16);
  5027. this._markAsUpdated();
  5028. }
  5029. /** @hidden */
  5030. Matrix.prototype._markAsUpdated = function () {
  5031. this.updateFlag = Matrix._updateFlagSeed++;
  5032. this._isIdentityDirty = true;
  5033. };
  5034. // Properties
  5035. /**
  5036. * Check if the current matrix is indentity
  5037. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5038. * @returns true is the matrix is the identity matrix
  5039. */
  5040. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5041. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5042. if (this._isIdentityDirty) {
  5043. this._isIdentityDirty = false;
  5044. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5045. this._isIdentity = false;
  5046. }
  5047. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5048. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5049. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5050. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5051. this._isIdentity = false;
  5052. }
  5053. else {
  5054. this._isIdentity = true;
  5055. }
  5056. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5057. this._isIdentity = false;
  5058. }
  5059. }
  5060. return this._isIdentity;
  5061. };
  5062. /**
  5063. * Gets the determinant of the matrix
  5064. * @returns the matrix determinant
  5065. */
  5066. Matrix.prototype.determinant = function () {
  5067. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5068. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5069. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5070. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5071. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5072. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5073. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5074. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5075. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5076. };
  5077. // Methods
  5078. /**
  5079. * Returns the matrix as a Float32Array
  5080. * @returns the matrix underlying array
  5081. */
  5082. Matrix.prototype.toArray = function () {
  5083. return this.m;
  5084. };
  5085. /**
  5086. * Returns the matrix as a Float32Array
  5087. * @returns the matrix underlying array.
  5088. */
  5089. Matrix.prototype.asArray = function () {
  5090. return this.toArray();
  5091. };
  5092. /**
  5093. * Inverts the current matrix in place
  5094. * @returns the current inverted matrix
  5095. */
  5096. Matrix.prototype.invert = function () {
  5097. this.invertToRef(this);
  5098. return this;
  5099. };
  5100. /**
  5101. * Sets all the matrix elements to zero
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.reset = function () {
  5105. for (var index = 0; index < 16; index++) {
  5106. this.m[index] = 0.0;
  5107. }
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds the current matrix with a second one
  5113. * @param other defines the matrix to add
  5114. * @returns a new matrix as the addition of the current matrix and the given one
  5115. */
  5116. Matrix.prototype.add = function (other) {
  5117. var result = new Matrix();
  5118. this.addToRef(other, result);
  5119. return result;
  5120. };
  5121. /**
  5122. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5123. * @param other defines the matrix to add
  5124. * @param result defines the target matrix
  5125. * @returns the current matrix
  5126. */
  5127. Matrix.prototype.addToRef = function (other, result) {
  5128. for (var index = 0; index < 16; index++) {
  5129. result.m[index] = this.m[index] + other.m[index];
  5130. }
  5131. result._markAsUpdated();
  5132. return this;
  5133. };
  5134. /**
  5135. * Adds in place the given matrix to the current matrix
  5136. * @param other defines the second operand
  5137. * @returns the current updated matrix
  5138. */
  5139. Matrix.prototype.addToSelf = function (other) {
  5140. for (var index = 0; index < 16; index++) {
  5141. this.m[index] += other.m[index];
  5142. }
  5143. this._markAsUpdated();
  5144. return this;
  5145. };
  5146. /**
  5147. * Sets the given matrix to the current inverted Matrix
  5148. * @param other defines the target matrix
  5149. * @returns the unmodified current matrix
  5150. */
  5151. Matrix.prototype.invertToRef = function (other) {
  5152. var l1 = this.m[0];
  5153. var l2 = this.m[1];
  5154. var l3 = this.m[2];
  5155. var l4 = this.m[3];
  5156. var l5 = this.m[4];
  5157. var l6 = this.m[5];
  5158. var l7 = this.m[6];
  5159. var l8 = this.m[7];
  5160. var l9 = this.m[8];
  5161. var l10 = this.m[9];
  5162. var l11 = this.m[10];
  5163. var l12 = this.m[11];
  5164. var l13 = this.m[12];
  5165. var l14 = this.m[13];
  5166. var l15 = this.m[14];
  5167. var l16 = this.m[15];
  5168. var l17 = (l11 * l16) - (l12 * l15);
  5169. var l18 = (l10 * l16) - (l12 * l14);
  5170. var l19 = (l10 * l15) - (l11 * l14);
  5171. var l20 = (l9 * l16) - (l12 * l13);
  5172. var l21 = (l9 * l15) - (l11 * l13);
  5173. var l22 = (l9 * l14) - (l10 * l13);
  5174. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5175. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5176. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5177. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5178. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5179. var l28 = (l7 * l16) - (l8 * l15);
  5180. var l29 = (l6 * l16) - (l8 * l14);
  5181. var l30 = (l6 * l15) - (l7 * l14);
  5182. var l31 = (l5 * l16) - (l8 * l13);
  5183. var l32 = (l5 * l15) - (l7 * l13);
  5184. var l33 = (l5 * l14) - (l6 * l13);
  5185. var l34 = (l7 * l12) - (l8 * l11);
  5186. var l35 = (l6 * l12) - (l8 * l10);
  5187. var l36 = (l6 * l11) - (l7 * l10);
  5188. var l37 = (l5 * l12) - (l8 * l9);
  5189. var l38 = (l5 * l11) - (l7 * l9);
  5190. var l39 = (l5 * l10) - (l6 * l9);
  5191. other.m[0] = l23 * l27;
  5192. other.m[4] = l24 * l27;
  5193. other.m[8] = l25 * l27;
  5194. other.m[12] = l26 * l27;
  5195. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5196. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5197. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5198. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5199. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5200. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5201. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5202. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5203. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5204. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5205. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5206. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5207. other._markAsUpdated();
  5208. return this;
  5209. };
  5210. /**
  5211. * Inserts the translation vector (using 3 floats) in the current matrix
  5212. * @param x defines the 1st component of the translation
  5213. * @param y defines the 2nd component of the translation
  5214. * @param z defines the 3rd component of the translation
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5218. this.m[12] = x;
  5219. this.m[13] = y;
  5220. this.m[14] = z;
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Inserts the translation vector in the current matrix
  5226. * @param vector3 defines the translation to insert
  5227. * @returns the current updated matrix
  5228. */
  5229. Matrix.prototype.setTranslation = function (vector3) {
  5230. this.m[12] = vector3.x;
  5231. this.m[13] = vector3.y;
  5232. this.m[14] = vector3.z;
  5233. this._markAsUpdated();
  5234. return this;
  5235. };
  5236. /**
  5237. * Gets the translation value of the current matrix
  5238. * @returns a new Vector3 as the extracted translation from the matrix
  5239. */
  5240. Matrix.prototype.getTranslation = function () {
  5241. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5242. };
  5243. /**
  5244. * Fill a Vector3 with the extracted translation from the matrix
  5245. * @param result defines the Vector3 where to store the translation
  5246. * @returns the current matrix
  5247. */
  5248. Matrix.prototype.getTranslationToRef = function (result) {
  5249. result.x = this.m[12];
  5250. result.y = this.m[13];
  5251. result.z = this.m[14];
  5252. return this;
  5253. };
  5254. /**
  5255. * Remove rotation and scaling part from the matrix
  5256. * @returns the updated matrix
  5257. */
  5258. Matrix.prototype.removeRotationAndScaling = function () {
  5259. this.setRowFromFloats(0, 1, 0, 0, 0);
  5260. this.setRowFromFloats(1, 0, 1, 0, 0);
  5261. this.setRowFromFloats(2, 0, 0, 1, 0);
  5262. return this;
  5263. };
  5264. /**
  5265. * Multiply two matrices
  5266. * @param other defines the second operand
  5267. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5268. */
  5269. Matrix.prototype.multiply = function (other) {
  5270. var result = new Matrix();
  5271. this.multiplyToRef(other, result);
  5272. return result;
  5273. };
  5274. /**
  5275. * Copy the current matrix from the given one
  5276. * @param other defines the source matrix
  5277. * @returns the current updated matrix
  5278. */
  5279. Matrix.prototype.copyFrom = function (other) {
  5280. for (var index = 0; index < 16; index++) {
  5281. this.m[index] = other.m[index];
  5282. }
  5283. this._markAsUpdated();
  5284. return this;
  5285. };
  5286. /**
  5287. * Populates the given array from the starting index with the current matrix values
  5288. * @param array defines the target array
  5289. * @param offset defines the offset in the target array where to start storing values
  5290. * @returns the current matrix
  5291. */
  5292. Matrix.prototype.copyToArray = function (array, offset) {
  5293. if (offset === void 0) { offset = 0; }
  5294. for (var index = 0; index < 16; index++) {
  5295. array[offset + index] = this.m[index];
  5296. }
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the matrix where to store the multiplication
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.multiplyToRef = function (other, result) {
  5306. this.multiplyToArray(other, result.m, 0);
  5307. result._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5312. * @param other defines the second operand
  5313. * @param result defines the array where to store the multiplication
  5314. * @param offset defines the offset in the target array where to start storing values
  5315. * @returns the current matrix
  5316. */
  5317. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5318. var tm0 = this.m[0];
  5319. var tm1 = this.m[1];
  5320. var tm2 = this.m[2];
  5321. var tm3 = this.m[3];
  5322. var tm4 = this.m[4];
  5323. var tm5 = this.m[5];
  5324. var tm6 = this.m[6];
  5325. var tm7 = this.m[7];
  5326. var tm8 = this.m[8];
  5327. var tm9 = this.m[9];
  5328. var tm10 = this.m[10];
  5329. var tm11 = this.m[11];
  5330. var tm12 = this.m[12];
  5331. var tm13 = this.m[13];
  5332. var tm14 = this.m[14];
  5333. var tm15 = this.m[15];
  5334. var om0 = other.m[0];
  5335. var om1 = other.m[1];
  5336. var om2 = other.m[2];
  5337. var om3 = other.m[3];
  5338. var om4 = other.m[4];
  5339. var om5 = other.m[5];
  5340. var om6 = other.m[6];
  5341. var om7 = other.m[7];
  5342. var om8 = other.m[8];
  5343. var om9 = other.m[9];
  5344. var om10 = other.m[10];
  5345. var om11 = other.m[11];
  5346. var om12 = other.m[12];
  5347. var om13 = other.m[13];
  5348. var om14 = other.m[14];
  5349. var om15 = other.m[15];
  5350. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5351. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5352. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5353. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5354. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5355. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5356. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5357. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5358. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5359. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5360. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5361. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5362. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5363. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5364. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5365. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5366. return this;
  5367. };
  5368. /**
  5369. * Check equality between this matrix and a second one
  5370. * @param value defines the second matrix to compare
  5371. * @returns true is the current matrix and the given one values are strictly equal
  5372. */
  5373. Matrix.prototype.equals = function (value) {
  5374. return value &&
  5375. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5376. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5377. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5378. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5379. };
  5380. /**
  5381. * Clone the current matrix
  5382. * @returns a new matrix from the current matrix
  5383. */
  5384. Matrix.prototype.clone = function () {
  5385. 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]);
  5386. };
  5387. /**
  5388. * Returns the name of the current matrix class
  5389. * @returns the string "Matrix"
  5390. */
  5391. Matrix.prototype.getClassName = function () {
  5392. return "Matrix";
  5393. };
  5394. /**
  5395. * Gets the hash code of the current matrix
  5396. * @returns the hash code
  5397. */
  5398. Matrix.prototype.getHashCode = function () {
  5399. var hash = this.m[0] || 0;
  5400. for (var i = 1; i < 16; i++) {
  5401. hash = (hash * 397) ^ (this.m[i] || 0);
  5402. }
  5403. return hash;
  5404. };
  5405. /**
  5406. * Decomposes the current Matrix into a translation, rotation and scaling components
  5407. * @param scale defines the scale vector3 given as a reference to update
  5408. * @param rotation defines the rotation quaternion given as a reference to update
  5409. * @param translation defines the translation vector3 given as a reference to update
  5410. * @returns true if operation was successful
  5411. */
  5412. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5413. if (translation) {
  5414. translation.x = this.m[12];
  5415. translation.y = this.m[13];
  5416. translation.z = this.m[14];
  5417. }
  5418. scale = scale || MathTmp.Vector3[0];
  5419. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5420. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5421. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5422. if (this.determinant() <= 0) {
  5423. scale.y *= -1;
  5424. }
  5425. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5426. if (rotation) {
  5427. rotation.x = 0;
  5428. rotation.y = 0;
  5429. rotation.z = 0;
  5430. rotation.w = 1;
  5431. }
  5432. return false;
  5433. }
  5434. if (rotation) {
  5435. 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]);
  5436. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5437. }
  5438. return true;
  5439. };
  5440. /**
  5441. * Gets specific row of the matrix
  5442. * @param index defines the number of the row to get
  5443. * @returns the index-th row of the current matrix as a new Vector4
  5444. */
  5445. Matrix.prototype.getRow = function (index) {
  5446. if (index < 0 || index > 3) {
  5447. return null;
  5448. }
  5449. var i = index * 4;
  5450. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5451. };
  5452. /**
  5453. * Sets the index-th row of the current matrix to the vector4 values
  5454. * @param index defines the number of the row to set
  5455. * @param row defines the target vector4
  5456. * @returns the updated current matrix
  5457. */
  5458. Matrix.prototype.setRow = function (index, row) {
  5459. if (index < 0 || index > 3) {
  5460. return this;
  5461. }
  5462. var i = index * 4;
  5463. this.m[i + 0] = row.x;
  5464. this.m[i + 1] = row.y;
  5465. this.m[i + 2] = row.z;
  5466. this.m[i + 3] = row.w;
  5467. this._markAsUpdated();
  5468. return this;
  5469. };
  5470. /**
  5471. * Compute the transpose of the matrix
  5472. * @returns the new transposed matrix
  5473. */
  5474. Matrix.prototype.transpose = function () {
  5475. return Matrix.Transpose(this);
  5476. };
  5477. /**
  5478. * Compute the transpose of the matrix and store it in a given matrix
  5479. * @param result defines the target matrix
  5480. * @returns the current matrix
  5481. */
  5482. Matrix.prototype.transposeToRef = function (result) {
  5483. Matrix.TransposeToRef(this, result);
  5484. return this;
  5485. };
  5486. /**
  5487. * Sets the index-th row of the current matrix with the given 4 x float values
  5488. * @param index defines the row index
  5489. * @param x defines the x component to set
  5490. * @param y defines the y component to set
  5491. * @param z defines the z component to set
  5492. * @param w defines the w component to set
  5493. * @returns the updated current matrix
  5494. */
  5495. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5496. if (index < 0 || index > 3) {
  5497. return this;
  5498. }
  5499. var i = index * 4;
  5500. this.m[i + 0] = x;
  5501. this.m[i + 1] = y;
  5502. this.m[i + 2] = z;
  5503. this.m[i + 3] = w;
  5504. this._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5509. * @param scale defines the scale factor
  5510. * @returns a new matrix
  5511. */
  5512. Matrix.prototype.scale = function (scale) {
  5513. var result = new Matrix();
  5514. this.scaleToRef(scale, result);
  5515. return result;
  5516. };
  5517. /**
  5518. * Scale the current matrix values by a factor to a given result matrix
  5519. * @param scale defines the scale factor
  5520. * @param result defines the matrix to store the result
  5521. * @returns the current matrix
  5522. */
  5523. Matrix.prototype.scaleToRef = function (scale, result) {
  5524. for (var index = 0; index < 16; index++) {
  5525. result.m[index] = this.m[index] * scale;
  5526. }
  5527. result._markAsUpdated();
  5528. return this;
  5529. };
  5530. /**
  5531. * Scale the current matrix values by a factor and add the result to a given matrix
  5532. * @param scale defines the scale factor
  5533. * @param result defines the Matrix to store the result
  5534. * @returns the current matrix
  5535. */
  5536. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5537. for (var index = 0; index < 16; index++) {
  5538. result.m[index] += this.m[index] * scale;
  5539. }
  5540. result._markAsUpdated();
  5541. return this;
  5542. };
  5543. /**
  5544. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5545. * @param ref matrix to store the result
  5546. */
  5547. Matrix.prototype.toNormalMatrix = function (ref) {
  5548. this.invertToRef(ref);
  5549. ref.transpose();
  5550. var m = ref.m;
  5551. 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);
  5552. };
  5553. /**
  5554. * Gets only rotation part of the current matrix
  5555. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5556. */
  5557. Matrix.prototype.getRotationMatrix = function () {
  5558. var result = Matrix.Identity();
  5559. this.getRotationMatrixToRef(result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5564. * @param result defines the target matrix to store data to
  5565. * @returns the current matrix
  5566. */
  5567. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5568. var m = this.m;
  5569. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5570. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5571. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5572. if (this.determinant() <= 0) {
  5573. sy *= -1;
  5574. }
  5575. if (sx === 0 || sy === 0 || sz === 0) {
  5576. Matrix.IdentityToRef(result);
  5577. }
  5578. else {
  5579. 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);
  5580. }
  5581. return this;
  5582. };
  5583. // Statics
  5584. /**
  5585. * Creates a matrix from an array
  5586. * @param array defines the source array
  5587. * @param offset defines an offset in the source array
  5588. * @returns a new Matrix set from the starting index of the given array
  5589. */
  5590. Matrix.FromArray = function (array, offset) {
  5591. var result = new Matrix();
  5592. if (!offset) {
  5593. offset = 0;
  5594. }
  5595. Matrix.FromArrayToRef(array, offset, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Copy the content of an array into a given matrix
  5600. * @param array defines the source array
  5601. * @param offset defines an offset in the source array
  5602. * @param result defines the target matrix
  5603. */
  5604. Matrix.FromArrayToRef = function (array, offset, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = array[index + offset];
  5607. }
  5608. result._markAsUpdated();
  5609. };
  5610. /**
  5611. * Stores an array into a matrix after having multiplied each component by a given factor
  5612. * @param array defines the source array
  5613. * @param offset defines the offset in the source array
  5614. * @param scale defines the scaling factor
  5615. * @param result defines the target matrix
  5616. */
  5617. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5618. for (var index = 0; index < 16; index++) {
  5619. result.m[index] = array[index + offset] * scale;
  5620. }
  5621. result._markAsUpdated();
  5622. };
  5623. /**
  5624. * Stores a list of values (16) inside a given matrix
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @param result defines the target matrix
  5642. */
  5643. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5644. result.m[0] = initialM11;
  5645. result.m[1] = initialM12;
  5646. result.m[2] = initialM13;
  5647. result.m[3] = initialM14;
  5648. result.m[4] = initialM21;
  5649. result.m[5] = initialM22;
  5650. result.m[6] = initialM23;
  5651. result.m[7] = initialM24;
  5652. result.m[8] = initialM31;
  5653. result.m[9] = initialM32;
  5654. result.m[10] = initialM33;
  5655. result.m[11] = initialM34;
  5656. result.m[12] = initialM41;
  5657. result.m[13] = initialM42;
  5658. result.m[14] = initialM43;
  5659. result.m[15] = initialM44;
  5660. result._markAsUpdated();
  5661. };
  5662. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5663. /**
  5664. * Gets an identity matrix that must not be updated
  5665. */
  5666. get: function () {
  5667. return Matrix._identityReadOnly;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. /**
  5673. * Creates new matrix from a list of values (16)
  5674. * @param initialM11 defines 1st value of 1st row
  5675. * @param initialM12 defines 2nd value of 1st row
  5676. * @param initialM13 defines 3rd value of 1st row
  5677. * @param initialM14 defines 4th value of 1st row
  5678. * @param initialM21 defines 1st value of 2nd row
  5679. * @param initialM22 defines 2nd value of 2nd row
  5680. * @param initialM23 defines 3rd value of 2nd row
  5681. * @param initialM24 defines 4th value of 2nd row
  5682. * @param initialM31 defines 1st value of 3rd row
  5683. * @param initialM32 defines 2nd value of 3rd row
  5684. * @param initialM33 defines 3rd value of 3rd row
  5685. * @param initialM34 defines 4th value of 3rd row
  5686. * @param initialM41 defines 1st value of 4th row
  5687. * @param initialM42 defines 2nd value of 4th row
  5688. * @param initialM43 defines 3rd value of 4th row
  5689. * @param initialM44 defines 4th value of 4th row
  5690. * @returns the new matrix
  5691. */
  5692. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5693. var result = new Matrix();
  5694. result.m[0] = initialM11;
  5695. result.m[1] = initialM12;
  5696. result.m[2] = initialM13;
  5697. result.m[3] = initialM14;
  5698. result.m[4] = initialM21;
  5699. result.m[5] = initialM22;
  5700. result.m[6] = initialM23;
  5701. result.m[7] = initialM24;
  5702. result.m[8] = initialM31;
  5703. result.m[9] = initialM32;
  5704. result.m[10] = initialM33;
  5705. result.m[11] = initialM34;
  5706. result.m[12] = initialM41;
  5707. result.m[13] = initialM42;
  5708. result.m[14] = initialM43;
  5709. result.m[15] = initialM44;
  5710. return result;
  5711. };
  5712. /**
  5713. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5714. * @param scale defines the scale vector3
  5715. * @param rotation defines the rotation quaternion
  5716. * @param translation defines the translation vector3
  5717. * @returns a new matrix
  5718. */
  5719. Matrix.Compose = function (scale, rotation, translation) {
  5720. var result = Matrix.Identity();
  5721. Matrix.ComposeToRef(scale, rotation, translation, result);
  5722. return result;
  5723. };
  5724. /**
  5725. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5726. * @param scale defines the scale vector3
  5727. * @param rotation defines the rotation quaternion
  5728. * @param translation defines the translation vector3
  5729. * @param result defines the target matrix
  5730. */
  5731. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5732. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5733. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5734. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5735. result.setTranslation(translation);
  5736. };
  5737. /**
  5738. * Creates a new identity matrix
  5739. * @returns a new identity matrix
  5740. */
  5741. Matrix.Identity = function () {
  5742. 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);
  5743. };
  5744. /**
  5745. * Creates a new identity matrix and stores the result in a given matrix
  5746. * @param result defines the target matrix
  5747. */
  5748. Matrix.IdentityToRef = function (result) {
  5749. 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);
  5750. };
  5751. /**
  5752. * Creates a new zero matrix
  5753. * @returns a new zero matrix
  5754. */
  5755. Matrix.Zero = function () {
  5756. 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);
  5757. };
  5758. /**
  5759. * Creates a new rotation matrix for "angle" radians around the X axis
  5760. * @param angle defines the angle (in radians) to use
  5761. * @return the new matrix
  5762. */
  5763. Matrix.RotationX = function (angle) {
  5764. var result = new Matrix();
  5765. Matrix.RotationXToRef(angle, result);
  5766. return result;
  5767. };
  5768. /**
  5769. * Creates a new matrix as the invert of a given matrix
  5770. * @param source defines the source matrix
  5771. * @returns the new matrix
  5772. */
  5773. Matrix.Invert = function (source) {
  5774. var result = new Matrix();
  5775. source.invertToRef(result);
  5776. return result;
  5777. };
  5778. /**
  5779. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5780. * @param angle defines the angle (in radians) to use
  5781. * @param result defines the target matrix
  5782. */
  5783. Matrix.RotationXToRef = function (angle, result) {
  5784. var s = Math.sin(angle);
  5785. var c = Math.cos(angle);
  5786. result.m[0] = 1.0;
  5787. result.m[15] = 1.0;
  5788. result.m[5] = c;
  5789. result.m[10] = c;
  5790. result.m[9] = -s;
  5791. result.m[6] = s;
  5792. result.m[1] = 0.0;
  5793. result.m[2] = 0.0;
  5794. result.m[3] = 0.0;
  5795. result.m[4] = 0.0;
  5796. result.m[7] = 0.0;
  5797. result.m[8] = 0.0;
  5798. result.m[11] = 0.0;
  5799. result.m[12] = 0.0;
  5800. result.m[13] = 0.0;
  5801. result.m[14] = 0.0;
  5802. result._markAsUpdated();
  5803. };
  5804. /**
  5805. * Creates a new rotation matrix for "angle" radians around the Y axis
  5806. * @param angle defines the angle (in radians) to use
  5807. * @return the new matrix
  5808. */
  5809. Matrix.RotationY = function (angle) {
  5810. var result = new Matrix();
  5811. Matrix.RotationYToRef(angle, result);
  5812. return result;
  5813. };
  5814. /**
  5815. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5816. * @param angle defines the angle (in radians) to use
  5817. * @param result defines the target matrix
  5818. */
  5819. Matrix.RotationYToRef = function (angle, result) {
  5820. var s = Math.sin(angle);
  5821. var c = Math.cos(angle);
  5822. result.m[5] = 1.0;
  5823. result.m[15] = 1.0;
  5824. result.m[0] = c;
  5825. result.m[2] = -s;
  5826. result.m[8] = s;
  5827. result.m[10] = c;
  5828. result.m[1] = 0.0;
  5829. result.m[3] = 0.0;
  5830. result.m[4] = 0.0;
  5831. result.m[6] = 0.0;
  5832. result.m[7] = 0.0;
  5833. result.m[9] = 0.0;
  5834. result.m[11] = 0.0;
  5835. result.m[12] = 0.0;
  5836. result.m[13] = 0.0;
  5837. result.m[14] = 0.0;
  5838. result._markAsUpdated();
  5839. };
  5840. /**
  5841. * Creates a new rotation matrix for "angle" radians around the Z axis
  5842. * @param angle defines the angle (in radians) to use
  5843. * @return the new matrix
  5844. */
  5845. Matrix.RotationZ = function (angle) {
  5846. var result = new Matrix();
  5847. Matrix.RotationZToRef(angle, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5852. * @param angle defines the angle (in radians) to use
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.RotationZToRef = function (angle, result) {
  5856. var s = Math.sin(angle);
  5857. var c = Math.cos(angle);
  5858. result.m[10] = 1.0;
  5859. result.m[15] = 1.0;
  5860. result.m[0] = c;
  5861. result.m[1] = s;
  5862. result.m[4] = -s;
  5863. result.m[5] = c;
  5864. result.m[2] = 0.0;
  5865. result.m[3] = 0.0;
  5866. result.m[6] = 0.0;
  5867. result.m[7] = 0.0;
  5868. result.m[8] = 0.0;
  5869. result.m[9] = 0.0;
  5870. result.m[11] = 0.0;
  5871. result.m[12] = 0.0;
  5872. result.m[13] = 0.0;
  5873. result.m[14] = 0.0;
  5874. result._markAsUpdated();
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @return the new matrix
  5881. */
  5882. Matrix.RotationAxis = function (axis, angle) {
  5883. var result = Matrix.Zero();
  5884. Matrix.RotationAxisToRef(axis, angle, result);
  5885. return result;
  5886. };
  5887. /**
  5888. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5889. * @param axis defines the axis to use
  5890. * @param angle defines the angle (in radians) to use
  5891. * @param result defines the target matrix
  5892. */
  5893. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5894. var s = Math.sin(-angle);
  5895. var c = Math.cos(-angle);
  5896. var c1 = 1 - c;
  5897. axis.normalize();
  5898. result.m[0] = (axis.x * axis.x) * c1 + c;
  5899. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5900. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5901. result.m[3] = 0.0;
  5902. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5903. result.m[5] = (axis.y * axis.y) * c1 + c;
  5904. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5905. result.m[7] = 0.0;
  5906. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5907. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5908. result.m[10] = (axis.z * axis.z) * c1 + c;
  5909. result.m[11] = 0.0;
  5910. result.m[15] = 1.0;
  5911. result._markAsUpdated();
  5912. };
  5913. /**
  5914. * Creates a rotation matrix
  5915. * @param yaw defines the yaw angle in radians (Y axis)
  5916. * @param pitch defines the pitch angle in radians (X axis)
  5917. * @param roll defines the roll angle in radians (X axis)
  5918. * @returns the new rotation matrix
  5919. */
  5920. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5921. var result = new Matrix();
  5922. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a rotation matrix and stores it in a given matrix
  5927. * @param yaw defines the yaw angle in radians (Y axis)
  5928. * @param pitch defines the pitch angle in radians (X axis)
  5929. * @param roll defines the roll angle in radians (X axis)
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5933. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5934. this._tempQuaternion.toRotationMatrix(result);
  5935. };
  5936. /**
  5937. * Creates a scaling matrix
  5938. * @param x defines the scale factor on X axis
  5939. * @param y defines the scale factor on Y axis
  5940. * @param z defines the scale factor on Z axis
  5941. * @returns the new matrix
  5942. */
  5943. Matrix.Scaling = function (x, y, z) {
  5944. var result = Matrix.Zero();
  5945. Matrix.ScalingToRef(x, y, z, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a scaling matrix and stores it in a given matrix
  5950. * @param x defines the scale factor on X axis
  5951. * @param y defines the scale factor on Y axis
  5952. * @param z defines the scale factor on Z axis
  5953. * @param result defines the target matrix
  5954. */
  5955. Matrix.ScalingToRef = function (x, y, z, result) {
  5956. result.m[0] = x;
  5957. result.m[1] = 0.0;
  5958. result.m[2] = 0.0;
  5959. result.m[3] = 0.0;
  5960. result.m[4] = 0.0;
  5961. result.m[5] = y;
  5962. result.m[6] = 0.0;
  5963. result.m[7] = 0.0;
  5964. result.m[8] = 0.0;
  5965. result.m[9] = 0.0;
  5966. result.m[10] = z;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result.m[15] = 1.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a translation matrix
  5976. * @param x defines the translation on X axis
  5977. * @param y defines the translation on Y axis
  5978. * @param z defines the translationon Z axis
  5979. * @returns the new matrix
  5980. */
  5981. Matrix.Translation = function (x, y, z) {
  5982. var result = Matrix.Identity();
  5983. Matrix.TranslationToRef(x, y, z, result);
  5984. return result;
  5985. };
  5986. /**
  5987. * Creates a translation matrix and stores it in a given matrix
  5988. * @param x defines the translation on X axis
  5989. * @param y defines the translation on Y axis
  5990. * @param z defines the translationon Z axis
  5991. * @param result defines the target matrix
  5992. */
  5993. Matrix.TranslationToRef = function (x, y, z, result) {
  5994. 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);
  5995. };
  5996. /**
  5997. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5998. * @param startValue defines the start value
  5999. * @param endValue defines the end value
  6000. * @param gradient defines the gradient factor
  6001. * @returns the new matrix
  6002. */
  6003. Matrix.Lerp = function (startValue, endValue, gradient) {
  6004. var result = Matrix.Zero();
  6005. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6006. return result;
  6007. };
  6008. /**
  6009. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6010. * @param startValue defines the start value
  6011. * @param endValue defines the end value
  6012. * @param gradient defines the gradient factor
  6013. * @param result defines the Matrix object where to store data
  6014. */
  6015. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6016. for (var index = 0; index < 16; index++) {
  6017. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6018. }
  6019. result._markAsUpdated();
  6020. };
  6021. /**
  6022. * Builds a new matrix whose values are computed by:
  6023. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6024. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6025. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6026. * @param startValue defines the first matrix
  6027. * @param endValue defines the second matrix
  6028. * @param gradient defines the gradient between the two matrices
  6029. * @returns the new matrix
  6030. */
  6031. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6032. var result = Matrix.Zero();
  6033. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6034. return result;
  6035. };
  6036. /**
  6037. * Update a matrix to values which are computed by:
  6038. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6039. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6040. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6041. * @param startValue defines the first matrix
  6042. * @param endValue defines the second matrix
  6043. * @param gradient defines the gradient between the two matrices
  6044. * @param result defines the target matrix
  6045. */
  6046. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6047. var startScale = MathTmp.Vector3[0];
  6048. var startRotation = MathTmp.Quaternion[0];
  6049. var startTranslation = MathTmp.Vector3[1];
  6050. startValue.decompose(startScale, startRotation, startTranslation);
  6051. var endScale = MathTmp.Vector3[2];
  6052. var endRotation = MathTmp.Quaternion[1];
  6053. var endTranslation = MathTmp.Vector3[3];
  6054. endValue.decompose(endScale, endRotation, endTranslation);
  6055. var resultScale = MathTmp.Vector3[4];
  6056. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6057. var resultRotation = MathTmp.Quaternion[2];
  6058. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6059. var resultTranslation = MathTmp.Vector3[5];
  6060. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6061. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6062. };
  6063. /**
  6064. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6065. * This function works in left handed mode
  6066. * @param eye defines the final position of the entity
  6067. * @param target defines where the entity should look at
  6068. * @param up defines the up vector for the entity
  6069. * @returns the new matrix
  6070. */
  6071. Matrix.LookAtLH = function (eye, target, up) {
  6072. var result = Matrix.Zero();
  6073. Matrix.LookAtLHToRef(eye, target, up, result);
  6074. return result;
  6075. };
  6076. /**
  6077. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6078. * This function works in left handed mode
  6079. * @param eye defines the final position of the entity
  6080. * @param target defines where the entity should look at
  6081. * @param up defines the up vector for the entity
  6082. * @param result defines the target matrix
  6083. */
  6084. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6085. // Z axis
  6086. target.subtractToRef(eye, this._zAxis);
  6087. this._zAxis.normalize();
  6088. // X axis
  6089. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6090. if (this._xAxis.lengthSquared() === 0) {
  6091. this._xAxis.x = 1.0;
  6092. }
  6093. else {
  6094. this._xAxis.normalize();
  6095. }
  6096. // Y axis
  6097. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6098. this._yAxis.normalize();
  6099. // Eye angles
  6100. var ex = -Vector3.Dot(this._xAxis, eye);
  6101. var ey = -Vector3.Dot(this._yAxis, eye);
  6102. var ez = -Vector3.Dot(this._zAxis, eye);
  6103. 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);
  6104. };
  6105. /**
  6106. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6107. * This function works in right handed mode
  6108. * @param eye defines the final position of the entity
  6109. * @param target defines where the entity should look at
  6110. * @param up defines the up vector for the entity
  6111. * @returns the new matrix
  6112. */
  6113. Matrix.LookAtRH = function (eye, target, up) {
  6114. var result = Matrix.Zero();
  6115. Matrix.LookAtRHToRef(eye, target, up, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6120. * This function works in right handed mode
  6121. * @param eye defines the final position of the entity
  6122. * @param target defines where the entity should look at
  6123. * @param up defines the up vector for the entity
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6127. // Z axis
  6128. eye.subtractToRef(target, this._zAxis);
  6129. this._zAxis.normalize();
  6130. // X axis
  6131. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6132. if (this._xAxis.lengthSquared() === 0) {
  6133. this._xAxis.x = 1.0;
  6134. }
  6135. else {
  6136. this._xAxis.normalize();
  6137. }
  6138. // Y axis
  6139. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6140. this._yAxis.normalize();
  6141. // Eye angles
  6142. var ex = -Vector3.Dot(this._xAxis, eye);
  6143. var ey = -Vector3.Dot(this._yAxis, eye);
  6144. var ez = -Vector3.Dot(this._zAxis, eye);
  6145. 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);
  6146. };
  6147. /**
  6148. * Create a left-handed orthographic projection matrix
  6149. * @param width defines the viewport width
  6150. * @param height defines the viewport height
  6151. * @param znear defines the near clip plane
  6152. * @param zfar defines the far clip plane
  6153. * @returns a new matrix as a left-handed orthographic projection matrix
  6154. */
  6155. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6156. var matrix = Matrix.Zero();
  6157. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6158. return matrix;
  6159. };
  6160. /**
  6161. * Store a left-handed orthographic projection to a given matrix
  6162. * @param width defines the viewport width
  6163. * @param height defines the viewport height
  6164. * @param znear defines the near clip plane
  6165. * @param zfar defines the far clip plane
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6169. var n = znear;
  6170. var f = zfar;
  6171. var a = 2.0 / width;
  6172. var b = 2.0 / height;
  6173. var c = 2.0 / (f - n);
  6174. var d = -(f + n) / (f - n);
  6175. 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);
  6176. };
  6177. /**
  6178. * Create a left-handed orthographic projection matrix
  6179. * @param left defines the viewport left coordinate
  6180. * @param right defines the viewport right coordinate
  6181. * @param bottom defines the viewport bottom coordinate
  6182. * @param top defines the viewport top coordinate
  6183. * @param znear defines the near clip plane
  6184. * @param zfar defines the far clip plane
  6185. * @returns a new matrix as a left-handed orthographic projection matrix
  6186. */
  6187. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6188. var matrix = Matrix.Zero();
  6189. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6190. return matrix;
  6191. };
  6192. /**
  6193. * Stores a left-handed orthographic projection into a given matrix
  6194. * @param left defines the viewport left coordinate
  6195. * @param right defines the viewport right coordinate
  6196. * @param bottom defines the viewport bottom coordinate
  6197. * @param top defines the viewport top coordinate
  6198. * @param znear defines the near clip plane
  6199. * @param zfar defines the far clip plane
  6200. * @param result defines the target matrix
  6201. */
  6202. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 / (right - left);
  6206. var b = 2.0 / (top - bottom);
  6207. var c = 2.0 / (f - n);
  6208. var d = -(f + n) / (f - n);
  6209. var i0 = (left + right) / (left - right);
  6210. var i1 = (top + bottom) / (bottom - top);
  6211. 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);
  6212. };
  6213. /**
  6214. * Creates a right-handed orthographic projection matrix
  6215. * @param left defines the viewport left coordinate
  6216. * @param right defines the viewport right coordinate
  6217. * @param bottom defines the viewport bottom coordinate
  6218. * @param top defines the viewport top coordinate
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a right-handed orthographic projection matrix
  6222. */
  6223. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6226. return matrix;
  6227. };
  6228. /**
  6229. * Stores a right-handed orthographic projection into a given matrix
  6230. * @param left defines the viewport left coordinate
  6231. * @param right defines the viewport right coordinate
  6232. * @param bottom defines the viewport bottom coordinate
  6233. * @param top defines the viewport top coordinate
  6234. * @param znear defines the near clip plane
  6235. * @param zfar defines the far clip plane
  6236. * @param result defines the target matrix
  6237. */
  6238. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6239. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6240. result.m[10] *= -1.0;
  6241. };
  6242. /**
  6243. * Creates a left-handed perspective projection matrix
  6244. * @param width defines the viewport width
  6245. * @param height defines the viewport height
  6246. * @param znear defines the near clip plane
  6247. * @param zfar defines the far clip plane
  6248. * @returns a new matrix as a left-handed perspective projection matrix
  6249. */
  6250. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6251. var matrix = Matrix.Zero();
  6252. var n = znear;
  6253. var f = zfar;
  6254. var a = 2.0 * n / width;
  6255. var b = 2.0 * n / height;
  6256. var c = (f + n) / (f - n);
  6257. var d = -2.0 * f * n / (f - n);
  6258. 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);
  6259. return matrix;
  6260. };
  6261. /**
  6262. * Creates a left-handed perspective projection matrix
  6263. * @param fov defines the horizontal field of view
  6264. * @param aspect defines the aspect ratio
  6265. * @param znear defines the near clip plane
  6266. * @param zfar defines the far clip plane
  6267. * @returns a new matrix as a left-handed perspective projection matrix
  6268. */
  6269. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6270. var matrix = Matrix.Zero();
  6271. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6272. return matrix;
  6273. };
  6274. /**
  6275. * Stores a left-handed perspective projection into a given matrix
  6276. * @param fov defines the horizontal field of view
  6277. * @param aspect defines the aspect ratio
  6278. * @param znear defines the near clip plane
  6279. * @param zfar defines the far clip plane
  6280. * @param result defines the target matrix
  6281. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6282. */
  6283. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6284. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6285. var n = znear;
  6286. var f = zfar;
  6287. var t = 1.0 / (Math.tan(fov * 0.5));
  6288. var a = isVerticalFovFixed ? (t / aspect) : t;
  6289. var b = isVerticalFovFixed ? t : (t * aspect);
  6290. var c = (f + n) / (f - n);
  6291. var d = -2.0 * f * n / (f - n);
  6292. 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);
  6293. };
  6294. /**
  6295. * Creates a right-handed perspective projection matrix
  6296. * @param fov defines the horizontal field of view
  6297. * @param aspect defines the aspect ratio
  6298. * @param znear defines the near clip plane
  6299. * @param zfar defines the far clip plane
  6300. * @returns a new matrix as a right-handed perspective projection matrix
  6301. */
  6302. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6303. var matrix = Matrix.Zero();
  6304. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6305. return matrix;
  6306. };
  6307. /**
  6308. * Stores a right-handed perspective projection into a given matrix
  6309. * @param fov defines the horizontal field of view
  6310. * @param aspect defines the aspect ratio
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6315. */
  6316. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6317. //alternatively this could be expressed as:
  6318. // m = PerspectiveFovLHToRef
  6319. // m[10] *= -1.0;
  6320. // m[11] *= -1.0;
  6321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6322. var n = znear;
  6323. var f = zfar;
  6324. var t = 1.0 / (Math.tan(fov * 0.5));
  6325. var a = isVerticalFovFixed ? (t / aspect) : t;
  6326. var b = isVerticalFovFixed ? t : (t * aspect);
  6327. var c = -(f + n) / (f - n);
  6328. var d = -2 * f * n / (f - n);
  6329. 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);
  6330. };
  6331. /**
  6332. * Stores a perspective projection for WebVR info a given matrix
  6333. * @param fov defines the field of view
  6334. * @param znear defines the near clip plane
  6335. * @param zfar defines the far clip plane
  6336. * @param result defines the target matrix
  6337. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6338. */
  6339. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6340. if (rightHanded === void 0) { rightHanded = false; }
  6341. var rightHandedFactor = rightHanded ? -1 : 1;
  6342. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6343. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6344. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6345. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6346. var xScale = 2.0 / (leftTan + rightTan);
  6347. var yScale = 2.0 / (upTan + downTan);
  6348. result.m[0] = xScale;
  6349. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6350. result.m[5] = yScale;
  6351. result.m[6] = result.m[7] = 0.0;
  6352. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6353. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6354. result.m[10] = -zfar / (znear - zfar);
  6355. result.m[11] = 1.0 * rightHandedFactor;
  6356. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6357. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6358. result._markAsUpdated();
  6359. };
  6360. /**
  6361. * Computes a complete transformation matrix
  6362. * @param viewport defines the viewport to use
  6363. * @param world defines the world matrix
  6364. * @param view defines the view matrix
  6365. * @param projection defines the projection matrix
  6366. * @param zmin defines the near clip plane
  6367. * @param zmax defines the far clip plane
  6368. * @returns the transformation matrix
  6369. */
  6370. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6371. var cw = viewport.width;
  6372. var ch = viewport.height;
  6373. var cx = viewport.x;
  6374. var cy = viewport.y;
  6375. 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);
  6376. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6377. };
  6378. /**
  6379. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix2x2 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1],
  6386. matrix.m[4], matrix.m[5]
  6387. ]);
  6388. };
  6389. /**
  6390. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6391. * @param matrix defines the matrix to use
  6392. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6393. */
  6394. Matrix.GetAsMatrix3x3 = function (matrix) {
  6395. return new Float32Array([
  6396. matrix.m[0], matrix.m[1], matrix.m[2],
  6397. matrix.m[4], matrix.m[5], matrix.m[6],
  6398. matrix.m[8], matrix.m[9], matrix.m[10]
  6399. ]);
  6400. };
  6401. /**
  6402. * Compute the transpose of a given matrix
  6403. * @param matrix defines the matrix to transpose
  6404. * @returns the new matrix
  6405. */
  6406. Matrix.Transpose = function (matrix) {
  6407. var result = new Matrix();
  6408. Matrix.TransposeToRef(matrix, result);
  6409. return result;
  6410. };
  6411. /**
  6412. * Compute the transpose of a matrix and store it in a target matrix
  6413. * @param matrix defines the matrix to transpose
  6414. * @param result defines the target matrix
  6415. */
  6416. Matrix.TransposeToRef = function (matrix, result) {
  6417. result.m[0] = matrix.m[0];
  6418. result.m[1] = matrix.m[4];
  6419. result.m[2] = matrix.m[8];
  6420. result.m[3] = matrix.m[12];
  6421. result.m[4] = matrix.m[1];
  6422. result.m[5] = matrix.m[5];
  6423. result.m[6] = matrix.m[9];
  6424. result.m[7] = matrix.m[13];
  6425. result.m[8] = matrix.m[2];
  6426. result.m[9] = matrix.m[6];
  6427. result.m[10] = matrix.m[10];
  6428. result.m[11] = matrix.m[14];
  6429. result.m[12] = matrix.m[3];
  6430. result.m[13] = matrix.m[7];
  6431. result.m[14] = matrix.m[11];
  6432. result.m[15] = matrix.m[15];
  6433. };
  6434. /**
  6435. * Computes a reflection matrix from a plane
  6436. * @param plane defines the reflection plane
  6437. * @returns a new matrix
  6438. */
  6439. Matrix.Reflection = function (plane) {
  6440. var matrix = new Matrix();
  6441. Matrix.ReflectionToRef(plane, matrix);
  6442. return matrix;
  6443. };
  6444. /**
  6445. * Computes a reflection matrix from a plane
  6446. * @param plane defines the reflection plane
  6447. * @param result defines the target matrix
  6448. */
  6449. Matrix.ReflectionToRef = function (plane, result) {
  6450. plane.normalize();
  6451. var x = plane.normal.x;
  6452. var y = plane.normal.y;
  6453. var z = plane.normal.z;
  6454. var temp = -2 * x;
  6455. var temp2 = -2 * y;
  6456. var temp3 = -2 * z;
  6457. result.m[0] = (temp * x) + 1;
  6458. result.m[1] = temp2 * x;
  6459. result.m[2] = temp3 * x;
  6460. result.m[3] = 0.0;
  6461. result.m[4] = temp * y;
  6462. result.m[5] = (temp2 * y) + 1;
  6463. result.m[6] = temp3 * y;
  6464. result.m[7] = 0.0;
  6465. result.m[8] = temp * z;
  6466. result.m[9] = temp2 * z;
  6467. result.m[10] = (temp3 * z) + 1;
  6468. result.m[11] = 0.0;
  6469. result.m[12] = temp * plane.d;
  6470. result.m[13] = temp2 * plane.d;
  6471. result.m[14] = temp3 * plane.d;
  6472. result.m[15] = 1.0;
  6473. result._markAsUpdated();
  6474. };
  6475. /**
  6476. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6477. * @param xaxis defines the value of the 1st axis
  6478. * @param yaxis defines the value of the 2nd axis
  6479. * @param zaxis defines the value of the 3rd axis
  6480. * @param result defines the target matrix
  6481. */
  6482. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6483. result.m[0] = xaxis.x;
  6484. result.m[1] = xaxis.y;
  6485. result.m[2] = xaxis.z;
  6486. result.m[3] = 0.0;
  6487. result.m[4] = yaxis.x;
  6488. result.m[5] = yaxis.y;
  6489. result.m[6] = yaxis.z;
  6490. result.m[7] = 0.0;
  6491. result.m[8] = zaxis.x;
  6492. result.m[9] = zaxis.y;
  6493. result.m[10] = zaxis.z;
  6494. result.m[11] = 0.0;
  6495. result.m[12] = 0.0;
  6496. result.m[13] = 0.0;
  6497. result.m[14] = 0.0;
  6498. result.m[15] = 1.0;
  6499. result._markAsUpdated();
  6500. };
  6501. /**
  6502. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6503. * @param quat defines the quaternion to use
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.FromQuaternionToRef = function (quat, result) {
  6507. var xx = quat.x * quat.x;
  6508. var yy = quat.y * quat.y;
  6509. var zz = quat.z * quat.z;
  6510. var xy = quat.x * quat.y;
  6511. var zw = quat.z * quat.w;
  6512. var zx = quat.z * quat.x;
  6513. var yw = quat.y * quat.w;
  6514. var yz = quat.y * quat.z;
  6515. var xw = quat.x * quat.w;
  6516. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6517. result.m[1] = 2.0 * (xy + zw);
  6518. result.m[2] = 2.0 * (zx - yw);
  6519. result.m[3] = 0.0;
  6520. result.m[4] = 2.0 * (xy - zw);
  6521. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6522. result.m[6] = 2.0 * (yz + xw);
  6523. result.m[7] = 0.0;
  6524. result.m[8] = 2.0 * (zx + yw);
  6525. result.m[9] = 2.0 * (yz - xw);
  6526. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6527. result.m[11] = 0.0;
  6528. result.m[12] = 0.0;
  6529. result.m[13] = 0.0;
  6530. result.m[14] = 0.0;
  6531. result.m[15] = 1.0;
  6532. result._markAsUpdated();
  6533. };
  6534. Matrix._tempQuaternion = new Quaternion();
  6535. Matrix._xAxis = Vector3.Zero();
  6536. Matrix._yAxis = Vector3.Zero();
  6537. Matrix._zAxis = Vector3.Zero();
  6538. Matrix._updateFlagSeed = 0;
  6539. Matrix._identityReadOnly = Matrix.Identity();
  6540. return Matrix;
  6541. }());
  6542. BABYLON.Matrix = Matrix;
  6543. var Plane = /** @class */ (function () {
  6544. /**
  6545. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6546. */
  6547. function Plane(a, b, c, d) {
  6548. this.normal = new Vector3(a, b, c);
  6549. this.d = d;
  6550. }
  6551. /**
  6552. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6553. */
  6554. Plane.prototype.asArray = function () {
  6555. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6556. };
  6557. // Methods
  6558. /**
  6559. * Returns a new plane copied from the current Plane.
  6560. */
  6561. Plane.prototype.clone = function () {
  6562. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6563. };
  6564. /**
  6565. * Returns the string "Plane".
  6566. */
  6567. Plane.prototype.getClassName = function () {
  6568. return "Plane";
  6569. };
  6570. /**
  6571. * Returns the Plane hash code.
  6572. */
  6573. Plane.prototype.getHashCode = function () {
  6574. var hash = this.normal.getHashCode();
  6575. hash = (hash * 397) ^ (this.d || 0);
  6576. return hash;
  6577. };
  6578. /**
  6579. * Normalize the current Plane in place.
  6580. * Returns the updated Plane.
  6581. */
  6582. Plane.prototype.normalize = function () {
  6583. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6584. var magnitude = 0.0;
  6585. if (norm !== 0) {
  6586. magnitude = 1.0 / norm;
  6587. }
  6588. this.normal.x *= magnitude;
  6589. this.normal.y *= magnitude;
  6590. this.normal.z *= magnitude;
  6591. this.d *= magnitude;
  6592. return this;
  6593. };
  6594. /**
  6595. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6596. */
  6597. Plane.prototype.transform = function (transformation) {
  6598. var transposedMatrix = Matrix.Transpose(transformation);
  6599. var x = this.normal.x;
  6600. var y = this.normal.y;
  6601. var z = this.normal.z;
  6602. var d = this.d;
  6603. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6604. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6605. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6606. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6607. return new Plane(normalX, normalY, normalZ, finalD);
  6608. };
  6609. /**
  6610. * Returns the dot product (float) of the point coordinates and the plane normal.
  6611. */
  6612. Plane.prototype.dotCoordinate = function (point) {
  6613. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6614. };
  6615. /**
  6616. * Updates the current Plane from the plane defined by the three given points.
  6617. * Returns the updated Plane.
  6618. */
  6619. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6620. var x1 = point2.x - point1.x;
  6621. var y1 = point2.y - point1.y;
  6622. var z1 = point2.z - point1.z;
  6623. var x2 = point3.x - point1.x;
  6624. var y2 = point3.y - point1.y;
  6625. var z2 = point3.z - point1.z;
  6626. var yz = (y1 * z2) - (z1 * y2);
  6627. var xz = (z1 * x2) - (x1 * z2);
  6628. var xy = (x1 * y2) - (y1 * x2);
  6629. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6630. var invPyth;
  6631. if (pyth !== 0) {
  6632. invPyth = 1.0 / pyth;
  6633. }
  6634. else {
  6635. invPyth = 0.0;
  6636. }
  6637. this.normal.x = yz * invPyth;
  6638. this.normal.y = xz * invPyth;
  6639. this.normal.z = xy * invPyth;
  6640. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6641. return this;
  6642. };
  6643. /**
  6644. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6645. */
  6646. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6647. var dot = Vector3.Dot(this.normal, direction);
  6648. return (dot <= epsilon);
  6649. };
  6650. /**
  6651. * Returns the signed distance (float) from the given point to the Plane.
  6652. */
  6653. Plane.prototype.signedDistanceTo = function (point) {
  6654. return Vector3.Dot(point, this.normal) + this.d;
  6655. };
  6656. // Statics
  6657. /**
  6658. * Returns a new Plane from the given array.
  6659. */
  6660. Plane.FromArray = function (array) {
  6661. return new Plane(array[0], array[1], array[2], array[3]);
  6662. };
  6663. /**
  6664. * Returns a new Plane defined by the three given points.
  6665. */
  6666. Plane.FromPoints = function (point1, point2, point3) {
  6667. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6668. result.copyFromPoints(point1, point2, point3);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns a new Plane the normal vector to this plane at the given origin point.
  6673. * Note : the vector "normal" is updated because normalized.
  6674. */
  6675. Plane.FromPositionAndNormal = function (origin, normal) {
  6676. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6677. normal.normalize();
  6678. result.normal = normal;
  6679. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6680. return result;
  6681. };
  6682. /**
  6683. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6684. */
  6685. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6686. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6687. return Vector3.Dot(point, normal) + d;
  6688. };
  6689. return Plane;
  6690. }());
  6691. BABYLON.Plane = Plane;
  6692. var Viewport = /** @class */ (function () {
  6693. /**
  6694. * Creates a Viewport object located at (x, y) and sized (width, height).
  6695. */
  6696. function Viewport(x, y, width, height) {
  6697. this.x = x;
  6698. this.y = y;
  6699. this.width = width;
  6700. this.height = height;
  6701. }
  6702. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6703. if (renderWidthOrEngine.getRenderWidth) {
  6704. var engine = renderWidthOrEngine;
  6705. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6706. }
  6707. var renderWidth = renderWidthOrEngine;
  6708. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6709. };
  6710. /**
  6711. * Returns a new Viewport copied from the current one.
  6712. */
  6713. Viewport.prototype.clone = function () {
  6714. return new Viewport(this.x, this.y, this.width, this.height);
  6715. };
  6716. return Viewport;
  6717. }());
  6718. BABYLON.Viewport = Viewport;
  6719. var Frustum = /** @class */ (function () {
  6720. function Frustum() {
  6721. }
  6722. /**
  6723. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6724. */
  6725. Frustum.GetPlanes = function (transform) {
  6726. var frustumPlanes = [];
  6727. for (var index = 0; index < 6; index++) {
  6728. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6729. }
  6730. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6731. return frustumPlanes;
  6732. };
  6733. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6734. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6735. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6736. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6737. frustumPlane.d = transform.m[15] + transform.m[14];
  6738. frustumPlane.normalize();
  6739. };
  6740. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6741. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6742. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6743. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6744. frustumPlane.d = transform.m[15] - transform.m[14];
  6745. frustumPlane.normalize();
  6746. };
  6747. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6748. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6749. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6750. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6751. frustumPlane.d = transform.m[15] + transform.m[12];
  6752. frustumPlane.normalize();
  6753. };
  6754. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6755. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6756. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6757. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6758. frustumPlane.d = transform.m[15] - transform.m[12];
  6759. frustumPlane.normalize();
  6760. };
  6761. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6762. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6763. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6764. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6765. frustumPlane.d = transform.m[15] - transform.m[13];
  6766. frustumPlane.normalize();
  6767. };
  6768. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6769. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6770. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6771. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6772. frustumPlane.d = transform.m[15] + transform.m[13];
  6773. frustumPlane.normalize();
  6774. };
  6775. /**
  6776. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6777. */
  6778. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6779. // Near
  6780. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6781. // Far
  6782. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6783. // Left
  6784. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6785. // Right
  6786. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6787. // Top
  6788. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6789. // Bottom
  6790. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6791. };
  6792. return Frustum;
  6793. }());
  6794. BABYLON.Frustum = Frustum;
  6795. /** Defines supported spaces */
  6796. var Space;
  6797. (function (Space) {
  6798. /** Local (object) space */
  6799. Space[Space["LOCAL"] = 0] = "LOCAL";
  6800. /** World space */
  6801. Space[Space["WORLD"] = 1] = "WORLD";
  6802. /** Bone space */
  6803. Space[Space["BONE"] = 2] = "BONE";
  6804. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6805. /** Defines the 3 main axes */
  6806. var Axis = /** @class */ (function () {
  6807. function Axis() {
  6808. }
  6809. /** X axis */
  6810. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6811. /** Y axis */
  6812. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6813. /** Z axis */
  6814. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6815. return Axis;
  6816. }());
  6817. BABYLON.Axis = Axis;
  6818. ;
  6819. var BezierCurve = /** @class */ (function () {
  6820. function BezierCurve() {
  6821. }
  6822. /**
  6823. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6824. */
  6825. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6826. // Extract X (which is equal to time here)
  6827. var f0 = 1 - 3 * x2 + 3 * x1;
  6828. var f1 = 3 * x2 - 6 * x1;
  6829. var f2 = 3 * x1;
  6830. var refinedT = t;
  6831. for (var i = 0; i < 5; i++) {
  6832. var refinedT2 = refinedT * refinedT;
  6833. var refinedT3 = refinedT2 * refinedT;
  6834. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6835. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6836. refinedT -= (x - t) * slope;
  6837. refinedT = Math.min(1, Math.max(0, refinedT));
  6838. }
  6839. // Resolve cubic bezier for the given x
  6840. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6841. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6842. Math.pow(refinedT, 3);
  6843. };
  6844. return BezierCurve;
  6845. }());
  6846. BABYLON.BezierCurve = BezierCurve;
  6847. /**
  6848. * Defines potential orientation for back face culling
  6849. */
  6850. var Orientation;
  6851. (function (Orientation) {
  6852. /**
  6853. * Clockwise
  6854. */
  6855. Orientation[Orientation["CW"] = 0] = "CW";
  6856. /** Counter clockwise */
  6857. Orientation[Orientation["CCW"] = 1] = "CCW";
  6858. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6859. /**
  6860. * Defines angle representation
  6861. */
  6862. var Angle = /** @class */ (function () {
  6863. /**
  6864. * Creates an Angle object of "radians" radians (float).
  6865. */
  6866. function Angle(radians) {
  6867. this._radians = radians;
  6868. if (this._radians < 0.0)
  6869. this._radians += (2.0 * Math.PI);
  6870. }
  6871. /**
  6872. * Get value in degrees
  6873. * @returns the Angle value in degrees (float)
  6874. */
  6875. Angle.prototype.degrees = function () {
  6876. return this._radians * 180.0 / Math.PI;
  6877. };
  6878. /**
  6879. * Get value in radians
  6880. * @returns the Angle value in radians (float)
  6881. */
  6882. Angle.prototype.radians = function () {
  6883. return this._radians;
  6884. };
  6885. /**
  6886. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6887. * @param a defines first vector
  6888. * @param b defines second vector
  6889. * @returns a new Angle
  6890. */
  6891. Angle.BetweenTwoPoints = function (a, b) {
  6892. var delta = b.subtract(a);
  6893. var theta = Math.atan2(delta.y, delta.x);
  6894. return new Angle(theta);
  6895. };
  6896. /**
  6897. * Gets a new Angle object from the given float in radians
  6898. * @param radians defines the angle value in radians
  6899. * @returns a new Angle
  6900. */
  6901. Angle.FromRadians = function (radians) {
  6902. return new Angle(radians);
  6903. };
  6904. /**
  6905. * Gets a new Angle object from the given float in degrees
  6906. * @param degrees defines the angle value in degrees
  6907. * @returns a new Angle
  6908. */
  6909. Angle.FromDegrees = function (degrees) {
  6910. return new Angle(degrees * Math.PI / 180.0);
  6911. };
  6912. return Angle;
  6913. }());
  6914. BABYLON.Angle = Angle;
  6915. var Arc2 = /** @class */ (function () {
  6916. /**
  6917. * Creates an Arc object from the three given points : start, middle and end.
  6918. */
  6919. function Arc2(startPoint, midPoint, endPoint) {
  6920. this.startPoint = startPoint;
  6921. this.midPoint = midPoint;
  6922. this.endPoint = endPoint;
  6923. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6924. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6925. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6926. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6927. 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);
  6928. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6929. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6930. var a1 = this.startAngle.degrees();
  6931. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6932. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6933. // angles correction
  6934. if (a2 - a1 > +180.0)
  6935. a2 -= 360.0;
  6936. if (a2 - a1 < -180.0)
  6937. a2 += 360.0;
  6938. if (a3 - a2 > +180.0)
  6939. a3 -= 360.0;
  6940. if (a3 - a2 < -180.0)
  6941. a3 += 360.0;
  6942. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6943. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6944. }
  6945. return Arc2;
  6946. }());
  6947. BABYLON.Arc2 = Arc2;
  6948. var Path2 = /** @class */ (function () {
  6949. /**
  6950. * Creates a Path2 object from the starting 2D coordinates x and y.
  6951. */
  6952. function Path2(x, y) {
  6953. this._points = new Array();
  6954. this._length = 0.0;
  6955. this.closed = false;
  6956. this._points.push(new Vector2(x, y));
  6957. }
  6958. /**
  6959. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6960. * Returns the updated Path2.
  6961. */
  6962. Path2.prototype.addLineTo = function (x, y) {
  6963. if (this.closed) {
  6964. return this;
  6965. }
  6966. var newPoint = new Vector2(x, y);
  6967. var previousPoint = this._points[this._points.length - 1];
  6968. this._points.push(newPoint);
  6969. this._length += newPoint.subtract(previousPoint).length();
  6970. return this;
  6971. };
  6972. /**
  6973. * 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.
  6974. * Returns the updated Path2.
  6975. */
  6976. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6977. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6978. if (this.closed) {
  6979. return this;
  6980. }
  6981. var startPoint = this._points[this._points.length - 1];
  6982. var midPoint = new Vector2(midX, midY);
  6983. var endPoint = new Vector2(endX, endY);
  6984. var arc = new Arc2(startPoint, midPoint, endPoint);
  6985. var increment = arc.angle.radians() / numberOfSegments;
  6986. if (arc.orientation === Orientation.CW)
  6987. increment *= -1;
  6988. var currentAngle = arc.startAngle.radians() + increment;
  6989. for (var i = 0; i < numberOfSegments; i++) {
  6990. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6991. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6992. this.addLineTo(x, y);
  6993. currentAngle += increment;
  6994. }
  6995. return this;
  6996. };
  6997. /**
  6998. * Closes the Path2.
  6999. * Returns the Path2.
  7000. */
  7001. Path2.prototype.close = function () {
  7002. this.closed = true;
  7003. return this;
  7004. };
  7005. /**
  7006. * Returns the Path2 total length (float).
  7007. */
  7008. Path2.prototype.length = function () {
  7009. var result = this._length;
  7010. if (!this.closed) {
  7011. var lastPoint = this._points[this._points.length - 1];
  7012. var firstPoint = this._points[0];
  7013. result += (firstPoint.subtract(lastPoint).length());
  7014. }
  7015. return result;
  7016. };
  7017. /**
  7018. * Returns the Path2 internal array of points.
  7019. */
  7020. Path2.prototype.getPoints = function () {
  7021. return this._points;
  7022. };
  7023. /**
  7024. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7025. */
  7026. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7027. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7028. return Vector2.Zero();
  7029. }
  7030. var lengthPosition = normalizedLengthPosition * this.length();
  7031. var previousOffset = 0;
  7032. for (var i = 0; i < this._points.length; i++) {
  7033. var j = (i + 1) % this._points.length;
  7034. var a = this._points[i];
  7035. var b = this._points[j];
  7036. var bToA = b.subtract(a);
  7037. var nextOffset = (bToA.length() + previousOffset);
  7038. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7039. var dir = bToA.normalize();
  7040. var localOffset = lengthPosition - previousOffset;
  7041. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7042. }
  7043. previousOffset = nextOffset;
  7044. }
  7045. return Vector2.Zero();
  7046. };
  7047. /**
  7048. * Returns a new Path2 starting at the coordinates (x, y).
  7049. */
  7050. Path2.StartingAt = function (x, y) {
  7051. return new Path2(x, y);
  7052. };
  7053. return Path2;
  7054. }());
  7055. BABYLON.Path2 = Path2;
  7056. var Path3D = /** @class */ (function () {
  7057. /**
  7058. * new Path3D(path, normal, raw)
  7059. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7060. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7061. * path : an array of Vector3, the curve axis of the Path3D
  7062. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7063. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7064. */
  7065. function Path3D(path, firstNormal, raw) {
  7066. if (firstNormal === void 0) { firstNormal = null; }
  7067. this.path = path;
  7068. this._curve = new Array();
  7069. this._distances = new Array();
  7070. this._tangents = new Array();
  7071. this._normals = new Array();
  7072. this._binormals = new Array();
  7073. for (var p = 0; p < path.length; p++) {
  7074. this._curve[p] = path[p].clone(); // hard copy
  7075. }
  7076. this._raw = raw || false;
  7077. this._compute(firstNormal);
  7078. }
  7079. /**
  7080. * Returns the Path3D array of successive Vector3 designing its curve.
  7081. */
  7082. Path3D.prototype.getCurve = function () {
  7083. return this._curve;
  7084. };
  7085. /**
  7086. * Returns an array populated with tangent vectors on each Path3D curve point.
  7087. */
  7088. Path3D.prototype.getTangents = function () {
  7089. return this._tangents;
  7090. };
  7091. /**
  7092. * Returns an array populated with normal vectors on each Path3D curve point.
  7093. */
  7094. Path3D.prototype.getNormals = function () {
  7095. return this._normals;
  7096. };
  7097. /**
  7098. * Returns an array populated with binormal vectors on each Path3D curve point.
  7099. */
  7100. Path3D.prototype.getBinormals = function () {
  7101. return this._binormals;
  7102. };
  7103. /**
  7104. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7105. */
  7106. Path3D.prototype.getDistances = function () {
  7107. return this._distances;
  7108. };
  7109. /**
  7110. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7111. * Returns the same object updated.
  7112. */
  7113. Path3D.prototype.update = function (path, firstNormal) {
  7114. if (firstNormal === void 0) { firstNormal = null; }
  7115. for (var p = 0; p < path.length; p++) {
  7116. this._curve[p].x = path[p].x;
  7117. this._curve[p].y = path[p].y;
  7118. this._curve[p].z = path[p].z;
  7119. }
  7120. this._compute(firstNormal);
  7121. return this;
  7122. };
  7123. // private function compute() : computes tangents, normals and binormals
  7124. Path3D.prototype._compute = function (firstNormal) {
  7125. var l = this._curve.length;
  7126. // first and last tangents
  7127. this._tangents[0] = this._getFirstNonNullVector(0);
  7128. if (!this._raw) {
  7129. this._tangents[0].normalize();
  7130. }
  7131. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7132. if (!this._raw) {
  7133. this._tangents[l - 1].normalize();
  7134. }
  7135. // normals and binormals at first point : arbitrary vector with _normalVector()
  7136. var tg0 = this._tangents[0];
  7137. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7138. this._normals[0] = pp0;
  7139. if (!this._raw) {
  7140. this._normals[0].normalize();
  7141. }
  7142. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7143. if (!this._raw) {
  7144. this._binormals[0].normalize();
  7145. }
  7146. this._distances[0] = 0.0;
  7147. // normals and binormals : next points
  7148. var prev; // previous vector (segment)
  7149. var cur; // current vector (segment)
  7150. var curTang; // current tangent
  7151. // previous normal
  7152. var prevBinor; // previous binormal
  7153. for (var i = 1; i < l; i++) {
  7154. // tangents
  7155. prev = this._getLastNonNullVector(i);
  7156. if (i < l - 1) {
  7157. cur = this._getFirstNonNullVector(i);
  7158. this._tangents[i] = prev.add(cur);
  7159. this._tangents[i].normalize();
  7160. }
  7161. this._distances[i] = this._distances[i - 1] + prev.length();
  7162. // normals and binormals
  7163. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7164. curTang = this._tangents[i];
  7165. prevBinor = this._binormals[i - 1];
  7166. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7167. if (!this._raw) {
  7168. this._normals[i].normalize();
  7169. }
  7170. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7171. if (!this._raw) {
  7172. this._binormals[i].normalize();
  7173. }
  7174. }
  7175. };
  7176. // private function getFirstNonNullVector(index)
  7177. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7178. Path3D.prototype._getFirstNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7181. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7182. i++;
  7183. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7184. }
  7185. return nNVector;
  7186. };
  7187. // private function getLastNonNullVector(index)
  7188. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7189. Path3D.prototype._getLastNonNullVector = function (index) {
  7190. var i = 1;
  7191. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7192. while (nLVector.length() === 0 && index > i + 1) {
  7193. i++;
  7194. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7195. }
  7196. return nLVector;
  7197. };
  7198. // private function normalVector(v0, vt, va) :
  7199. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7200. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7201. Path3D.prototype._normalVector = function (v0, vt, va) {
  7202. var normal0;
  7203. var tgl = vt.length();
  7204. if (tgl === 0.0) {
  7205. tgl = 1.0;
  7206. }
  7207. if (va === undefined || va === null) {
  7208. var point;
  7209. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7210. point = new Vector3(0.0, -1.0, 0.0);
  7211. }
  7212. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7213. point = new Vector3(1.0, 0.0, 0.0);
  7214. }
  7215. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7216. point = new Vector3(0.0, 0.0, 1.0);
  7217. }
  7218. else {
  7219. point = Vector3.Zero();
  7220. }
  7221. normal0 = Vector3.Cross(vt, point);
  7222. }
  7223. else {
  7224. normal0 = Vector3.Cross(vt, va);
  7225. Vector3.CrossToRef(normal0, vt, normal0);
  7226. }
  7227. normal0.normalize();
  7228. return normal0;
  7229. };
  7230. return Path3D;
  7231. }());
  7232. BABYLON.Path3D = Path3D;
  7233. var Curve3 = /** @class */ (function () {
  7234. /**
  7235. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7236. * A Curve3 is designed from a series of successive Vector3.
  7237. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7238. */
  7239. function Curve3(points) {
  7240. this._length = 0.0;
  7241. this._points = points;
  7242. this._length = this._computeLength(points);
  7243. }
  7244. /**
  7245. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7246. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7247. * @param v1 (Vector3) the control point
  7248. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7249. * @param nbPoints (integer) the wanted number of points in the curve
  7250. */
  7251. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7252. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7253. var bez = new Array();
  7254. var equation = function (t, val0, val1, val2) {
  7255. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7256. return res;
  7257. };
  7258. for (var i = 0; i <= nbPoints; i++) {
  7259. 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)));
  7260. }
  7261. return new Curve3(bez);
  7262. };
  7263. /**
  7264. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7265. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7266. * @param v1 (Vector3) the first control point
  7267. * @param v2 (Vector3) the second control point
  7268. * @param v3 (Vector3) the end point of the Cubic Bezier
  7269. * @param nbPoints (integer) the wanted number of points in the curve
  7270. */
  7271. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7272. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7273. var bez = new Array();
  7274. var equation = function (t, val0, val1, val2, val3) {
  7275. 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;
  7276. return res;
  7277. };
  7278. for (var i = 0; i <= nbPoints; i++) {
  7279. 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)));
  7280. }
  7281. return new Curve3(bez);
  7282. };
  7283. /**
  7284. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7285. * @param p1 (Vector3) the origin point of the Hermite Spline
  7286. * @param t1 (Vector3) the tangent vector at the origin point
  7287. * @param p2 (Vector3) the end point of the Hermite Spline
  7288. * @param t2 (Vector3) the tangent vector at the end point
  7289. * @param nbPoints (integer) the wanted number of points in the curve
  7290. */
  7291. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7292. var hermite = new Array();
  7293. var step = 1.0 / nbPoints;
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7296. }
  7297. return new Curve3(hermite);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a CatmullRom Spline curve :
  7301. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7302. * @param nbPoints (integer) the wanted number of points between each curve control points
  7303. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7304. */
  7305. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7306. var catmullRom = new Array();
  7307. var step = 1.0 / nbPoints;
  7308. var amount = 0.0;
  7309. if (closed) {
  7310. var pointsCount = points.length;
  7311. for (var i = 0; i < pointsCount; i++) {
  7312. amount = 0;
  7313. for (var c = 0; c < nbPoints; c++) {
  7314. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7315. amount += step;
  7316. }
  7317. }
  7318. catmullRom.push(catmullRom[0]);
  7319. }
  7320. else {
  7321. var totalPoints = new Array();
  7322. totalPoints.push(points[0].clone());
  7323. Array.prototype.push.apply(totalPoints, points);
  7324. totalPoints.push(points[points.length - 1].clone());
  7325. for (var i = 0; i < totalPoints.length - 3; i++) {
  7326. amount = 0;
  7327. for (var c = 0; c < nbPoints; c++) {
  7328. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7329. amount += step;
  7330. }
  7331. }
  7332. i--;
  7333. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7334. }
  7335. return new Curve3(catmullRom);
  7336. };
  7337. /**
  7338. * Returns the Curve3 stored array of successive Vector3
  7339. */
  7340. Curve3.prototype.getPoints = function () {
  7341. return this._points;
  7342. };
  7343. /**
  7344. * Returns the computed length (float) of the curve.
  7345. */
  7346. Curve3.prototype.length = function () {
  7347. return this._length;
  7348. };
  7349. /**
  7350. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7351. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7352. * curveA and curveB keep unchanged.
  7353. */
  7354. Curve3.prototype.continue = function (curve) {
  7355. var lastPoint = this._points[this._points.length - 1];
  7356. var continuedPoints = this._points.slice();
  7357. var curvePoints = curve.getPoints();
  7358. for (var i = 1; i < curvePoints.length; i++) {
  7359. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7360. }
  7361. var continuedCurve = new Curve3(continuedPoints);
  7362. return continuedCurve;
  7363. };
  7364. Curve3.prototype._computeLength = function (path) {
  7365. var l = 0;
  7366. for (var i = 1; i < path.length; i++) {
  7367. l += (path[i].subtract(path[i - 1])).length();
  7368. }
  7369. return l;
  7370. };
  7371. return Curve3;
  7372. }());
  7373. BABYLON.Curve3 = Curve3;
  7374. // Vertex formats
  7375. var PositionNormalVertex = /** @class */ (function () {
  7376. function PositionNormalVertex(position, normal) {
  7377. if (position === void 0) { position = Vector3.Zero(); }
  7378. if (normal === void 0) { normal = Vector3.Up(); }
  7379. this.position = position;
  7380. this.normal = normal;
  7381. }
  7382. PositionNormalVertex.prototype.clone = function () {
  7383. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7384. };
  7385. return PositionNormalVertex;
  7386. }());
  7387. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7388. var PositionNormalTextureVertex = /** @class */ (function () {
  7389. function PositionNormalTextureVertex(position, normal, uv) {
  7390. if (position === void 0) { position = Vector3.Zero(); }
  7391. if (normal === void 0) { normal = Vector3.Up(); }
  7392. if (uv === void 0) { uv = Vector2.Zero(); }
  7393. this.position = position;
  7394. this.normal = normal;
  7395. this.uv = uv;
  7396. }
  7397. PositionNormalTextureVertex.prototype.clone = function () {
  7398. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7399. };
  7400. return PositionNormalTextureVertex;
  7401. }());
  7402. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7403. // Temporary pre-allocated objects for engine internal use
  7404. // usage in any internal function :
  7405. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7406. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7407. var Tmp = /** @class */ (function () {
  7408. function Tmp() {
  7409. }
  7410. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7411. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7412. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7413. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7414. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7415. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7416. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7417. Matrix.Zero(), Matrix.Zero(),
  7418. Matrix.Zero(), Matrix.Zero(),
  7419. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7420. return Tmp;
  7421. }());
  7422. BABYLON.Tmp = Tmp;
  7423. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7424. var MathTmp = /** @class */ (function () {
  7425. function MathTmp() {
  7426. }
  7427. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7428. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7429. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7430. return MathTmp;
  7431. }());
  7432. })(BABYLON || (BABYLON = {}));
  7433. //# sourceMappingURL=babylon.math.js.map
  7434. var BABYLON;
  7435. (function (BABYLON) {
  7436. var Scalar = /** @class */ (function () {
  7437. function Scalar() {
  7438. }
  7439. /**
  7440. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7441. */
  7442. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7443. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7444. var num = a - b;
  7445. return -epsilon <= num && num <= epsilon;
  7446. };
  7447. /**
  7448. * Returns a string : the upper case translation of the number i to hexadecimal.
  7449. */
  7450. Scalar.ToHex = function (i) {
  7451. var str = i.toString(16);
  7452. if (i <= 15) {
  7453. return ("0" + str).toUpperCase();
  7454. }
  7455. return str.toUpperCase();
  7456. };
  7457. /**
  7458. * Returns -1 if value is negative and +1 is value is positive.
  7459. * Returns the value itself if it's equal to zero.
  7460. */
  7461. Scalar.Sign = function (value) {
  7462. value = +value; // convert to a number
  7463. if (value === 0 || isNaN(value))
  7464. return value;
  7465. return value > 0 ? 1 : -1;
  7466. };
  7467. /**
  7468. * Returns the value itself if it's between min and max.
  7469. * Returns min if the value is lower than min.
  7470. * Returns max if the value is greater than max.
  7471. */
  7472. Scalar.Clamp = function (value, min, max) {
  7473. if (min === void 0) { min = 0; }
  7474. if (max === void 0) { max = 1; }
  7475. return Math.min(max, Math.max(min, value));
  7476. };
  7477. /**
  7478. * Returns the log2 of value.
  7479. */
  7480. Scalar.Log2 = function (value) {
  7481. return Math.log(value) * Math.LOG2E;
  7482. };
  7483. /**
  7484. * Loops the value, so that it is never larger than length and never smaller than 0.
  7485. *
  7486. * This is similar to the modulo operator but it works with floating point numbers.
  7487. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7488. * With t = 5 and length = 2.5, the result would be 0.0.
  7489. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7490. */
  7491. Scalar.Repeat = function (value, length) {
  7492. return value - Math.floor(value / length) * length;
  7493. };
  7494. /**
  7495. * Normalize the value between 0.0 and 1.0 using min and max values
  7496. */
  7497. Scalar.Normalize = function (value, min, max) {
  7498. return (value - min) / (max - min);
  7499. };
  7500. /**
  7501. * Denormalize the value from 0.0 and 1.0 using min and max values
  7502. */
  7503. Scalar.Denormalize = function (normalized, min, max) {
  7504. return (normalized * (max - min) + min);
  7505. };
  7506. /**
  7507. * Calculates the shortest difference between two given angles given in degrees.
  7508. */
  7509. Scalar.DeltaAngle = function (current, target) {
  7510. var num = Scalar.Repeat(target - current, 360.0);
  7511. if (num > 180.0) {
  7512. num -= 360.0;
  7513. }
  7514. return num;
  7515. };
  7516. /**
  7517. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7518. *
  7519. * The returned value will move back and forth between 0 and length
  7520. */
  7521. Scalar.PingPong = function (tx, length) {
  7522. var t = Scalar.Repeat(tx, length * 2.0);
  7523. return length - Math.abs(t - length);
  7524. };
  7525. /**
  7526. * Interpolates between min and max with smoothing at the limits.
  7527. *
  7528. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7529. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7530. */
  7531. Scalar.SmoothStep = function (from, to, tx) {
  7532. var t = Scalar.Clamp(tx);
  7533. t = -2.0 * t * t * t + 3.0 * t * t;
  7534. return to * t + from * (1.0 - t);
  7535. };
  7536. /**
  7537. * Moves a value current towards target.
  7538. *
  7539. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7540. * Negative values of maxDelta pushes the value away from target.
  7541. */
  7542. Scalar.MoveTowards = function (current, target, maxDelta) {
  7543. var result = 0;
  7544. if (Math.abs(target - current) <= maxDelta) {
  7545. result = target;
  7546. }
  7547. else {
  7548. result = current + Scalar.Sign(target - current) * maxDelta;
  7549. }
  7550. return result;
  7551. };
  7552. /**
  7553. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7554. *
  7555. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7556. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7557. */
  7558. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7559. var num = Scalar.DeltaAngle(current, target);
  7560. var result = 0;
  7561. if (-maxDelta < num && num < maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. target = current + num;
  7566. result = Scalar.MoveTowards(current, target, maxDelta);
  7567. }
  7568. return result;
  7569. };
  7570. /**
  7571. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7572. */
  7573. Scalar.Lerp = function (start, end, amount) {
  7574. return start + ((end - start) * amount);
  7575. };
  7576. /**
  7577. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7578. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7579. */
  7580. Scalar.LerpAngle = function (start, end, amount) {
  7581. var num = Scalar.Repeat(end - start, 360.0);
  7582. if (num > 180.0) {
  7583. num -= 360.0;
  7584. }
  7585. return start + num * Scalar.Clamp(amount);
  7586. };
  7587. /**
  7588. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7589. */
  7590. Scalar.InverseLerp = function (a, b, value) {
  7591. var result = 0;
  7592. if (a != b) {
  7593. result = Scalar.Clamp((value - a) / (b - a));
  7594. }
  7595. else {
  7596. result = 0.0;
  7597. }
  7598. return result;
  7599. };
  7600. /**
  7601. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7602. */
  7603. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7604. var squared = amount * amount;
  7605. var cubed = amount * squared;
  7606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7608. var part3 = (cubed - (2.0 * squared)) + amount;
  7609. var part4 = cubed - squared;
  7610. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7611. };
  7612. /**
  7613. * Returns a random float number between and min and max values
  7614. */
  7615. Scalar.RandomRange = function (min, max) {
  7616. if (min === max)
  7617. return min;
  7618. return ((Math.random() * (max - min)) + min);
  7619. };
  7620. /**
  7621. * This function returns percentage of a number in a given range.
  7622. *
  7623. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7624. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7625. */
  7626. Scalar.RangeToPercent = function (number, min, max) {
  7627. return ((number - min) / (max - min));
  7628. };
  7629. /**
  7630. * This function returns number that corresponds to the percentage in a given range.
  7631. *
  7632. * PercentToRange(0.34,0,100) will return 34.
  7633. */
  7634. Scalar.PercentToRange = function (percent, min, max) {
  7635. return ((max - min) * percent + min);
  7636. };
  7637. /**
  7638. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7639. * @param angle The angle to normalize in radian.
  7640. * @return The converted angle.
  7641. */
  7642. Scalar.NormalizeRadians = function (angle) {
  7643. // More precise but slower version kept for reference.
  7644. // angle = angle % Tools.TwoPi;
  7645. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7646. //if (angle > Math.PI) {
  7647. // angle -= Tools.TwoPi;
  7648. //}
  7649. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7650. return angle;
  7651. };
  7652. /**
  7653. * Two pi constants convenient for computation.
  7654. */
  7655. Scalar.TwoPi = Math.PI * 2;
  7656. return Scalar;
  7657. }());
  7658. BABYLON.Scalar = Scalar;
  7659. })(BABYLON || (BABYLON = {}));
  7660. //# sourceMappingURL=babylon.math.scalar.js.map
  7661. //# sourceMappingURL=babylon.mixins.js.map
  7662. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7663. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7664. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7665. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7666. //# sourceMappingURL=babylon.webgl2.js.map
  7667. var BABYLON;
  7668. (function (BABYLON) {
  7669. var __decoratorInitialStore = {};
  7670. var __mergedStore = {};
  7671. var _copySource = function (creationFunction, source, instanciate) {
  7672. var destination = creationFunction();
  7673. // Tags
  7674. if (BABYLON.Tags) {
  7675. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7676. }
  7677. var classStore = getMergedStore(destination);
  7678. // Properties
  7679. for (var property in classStore) {
  7680. var propertyDescriptor = classStore[property];
  7681. var sourceProperty = source[property];
  7682. var propertyType = propertyDescriptor.type;
  7683. if (sourceProperty !== undefined && sourceProperty !== null) {
  7684. switch (propertyType) {
  7685. case 0: // Value
  7686. case 6: // Mesh reference
  7687. case 11: // Camera reference
  7688. destination[property] = sourceProperty;
  7689. break;
  7690. case 1: // Texture
  7691. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7692. break;
  7693. case 2: // Color3
  7694. case 3: // FresnelParameters
  7695. case 4: // Vector2
  7696. case 5: // Vector3
  7697. case 7: // Color Curves
  7698. case 10: // Quaternion
  7699. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7700. break;
  7701. }
  7702. }
  7703. }
  7704. return destination;
  7705. };
  7706. function getDirectStore(target) {
  7707. var classKey = target.getClassName();
  7708. if (!__decoratorInitialStore[classKey]) {
  7709. __decoratorInitialStore[classKey] = {};
  7710. }
  7711. return __decoratorInitialStore[classKey];
  7712. }
  7713. /**
  7714. * Return the list of properties flagged as serializable
  7715. * @param target: host object
  7716. */
  7717. function getMergedStore(target) {
  7718. var classKey = target.getClassName();
  7719. if (__mergedStore[classKey]) {
  7720. return __mergedStore[classKey];
  7721. }
  7722. __mergedStore[classKey] = {};
  7723. var store = __mergedStore[classKey];
  7724. var currentTarget = target;
  7725. var currentKey = classKey;
  7726. while (currentKey) {
  7727. var initialStore = __decoratorInitialStore[currentKey];
  7728. for (var property in initialStore) {
  7729. store[property] = initialStore[property];
  7730. }
  7731. var parent_1 = void 0;
  7732. var done = false;
  7733. do {
  7734. parent_1 = Object.getPrototypeOf(currentTarget);
  7735. if (!parent_1.getClassName) {
  7736. done = true;
  7737. break;
  7738. }
  7739. if (parent_1.getClassName() !== currentKey) {
  7740. break;
  7741. }
  7742. currentTarget = parent_1;
  7743. } while (parent_1);
  7744. if (done) {
  7745. break;
  7746. }
  7747. currentKey = parent_1.getClassName();
  7748. currentTarget = parent_1;
  7749. }
  7750. return store;
  7751. }
  7752. function generateSerializableMember(type, sourceName) {
  7753. return function (target, propertyKey) {
  7754. var classStore = getDirectStore(target);
  7755. if (!classStore[propertyKey]) {
  7756. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7757. }
  7758. };
  7759. }
  7760. function generateExpandMember(setCallback, targetKey) {
  7761. if (targetKey === void 0) { targetKey = null; }
  7762. return function (target, propertyKey) {
  7763. var key = targetKey || ("_" + propertyKey);
  7764. Object.defineProperty(target, propertyKey, {
  7765. get: function () {
  7766. return this[key];
  7767. },
  7768. set: function (value) {
  7769. if (this[key] === value) {
  7770. return;
  7771. }
  7772. this[key] = value;
  7773. target[setCallback].apply(this);
  7774. },
  7775. enumerable: true,
  7776. configurable: true
  7777. });
  7778. };
  7779. }
  7780. function expandToProperty(callback, targetKey) {
  7781. if (targetKey === void 0) { targetKey = null; }
  7782. return generateExpandMember(callback, targetKey);
  7783. }
  7784. BABYLON.expandToProperty = expandToProperty;
  7785. function serialize(sourceName) {
  7786. return generateSerializableMember(0, sourceName); // value member
  7787. }
  7788. BABYLON.serialize = serialize;
  7789. function serializeAsTexture(sourceName) {
  7790. return generateSerializableMember(1, sourceName); // texture member
  7791. }
  7792. BABYLON.serializeAsTexture = serializeAsTexture;
  7793. function serializeAsColor3(sourceName) {
  7794. return generateSerializableMember(2, sourceName); // color3 member
  7795. }
  7796. BABYLON.serializeAsColor3 = serializeAsColor3;
  7797. function serializeAsFresnelParameters(sourceName) {
  7798. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7799. }
  7800. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7801. function serializeAsVector2(sourceName) {
  7802. return generateSerializableMember(4, sourceName); // vector2 member
  7803. }
  7804. BABYLON.serializeAsVector2 = serializeAsVector2;
  7805. function serializeAsVector3(sourceName) {
  7806. return generateSerializableMember(5, sourceName); // vector3 member
  7807. }
  7808. BABYLON.serializeAsVector3 = serializeAsVector3;
  7809. function serializeAsMeshReference(sourceName) {
  7810. return generateSerializableMember(6, sourceName); // mesh reference member
  7811. }
  7812. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7813. function serializeAsColorCurves(sourceName) {
  7814. return generateSerializableMember(7, sourceName); // color curves
  7815. }
  7816. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7817. function serializeAsColor4(sourceName) {
  7818. return generateSerializableMember(8, sourceName); // color 4
  7819. }
  7820. BABYLON.serializeAsColor4 = serializeAsColor4;
  7821. function serializeAsImageProcessingConfiguration(sourceName) {
  7822. return generateSerializableMember(9, sourceName); // image processing
  7823. }
  7824. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7825. function serializeAsQuaternion(sourceName) {
  7826. return generateSerializableMember(10, sourceName); // quaternion member
  7827. }
  7828. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7829. /**
  7830. * Decorator used to define property that can be serialized as reference to a camera
  7831. * @param sourceName defines the name of the property to decorate
  7832. */
  7833. function serializeAsCameraReference(sourceName) {
  7834. return generateSerializableMember(11, sourceName); // camera reference member
  7835. }
  7836. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7837. var SerializationHelper = /** @class */ (function () {
  7838. function SerializationHelper() {
  7839. }
  7840. SerializationHelper.Serialize = function (entity, serializationObject) {
  7841. if (!serializationObject) {
  7842. serializationObject = {};
  7843. }
  7844. // Tags
  7845. if (BABYLON.Tags) {
  7846. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7847. }
  7848. var serializedProperties = getMergedStore(entity);
  7849. // Properties
  7850. for (var property in serializedProperties) {
  7851. var propertyDescriptor = serializedProperties[property];
  7852. var targetPropertyName = propertyDescriptor.sourceName || property;
  7853. var propertyType = propertyDescriptor.type;
  7854. var sourceProperty = entity[property];
  7855. if (sourceProperty !== undefined && sourceProperty !== null) {
  7856. switch (propertyType) {
  7857. case 0: // Value
  7858. serializationObject[targetPropertyName] = sourceProperty;
  7859. break;
  7860. case 1: // Texture
  7861. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7862. break;
  7863. case 2: // Color3
  7864. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7865. break;
  7866. case 3: // FresnelParameters
  7867. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7868. break;
  7869. case 4: // Vector2
  7870. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7871. break;
  7872. case 5: // Vector3
  7873. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7874. break;
  7875. case 6: // Mesh reference
  7876. serializationObject[targetPropertyName] = sourceProperty.id;
  7877. break;
  7878. case 7: // Color Curves
  7879. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7880. break;
  7881. case 8: // Color 4
  7882. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7883. break;
  7884. case 9: // Image Processing
  7885. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7886. break;
  7887. case 10: // Quaternion
  7888. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7889. break;
  7890. case 11: // Camera reference
  7891. serializationObject[targetPropertyName] = sourceProperty.id;
  7892. break;
  7893. }
  7894. }
  7895. }
  7896. return serializationObject;
  7897. };
  7898. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7899. if (rootUrl === void 0) { rootUrl = null; }
  7900. var destination = creationFunction();
  7901. if (!rootUrl) {
  7902. rootUrl = "";
  7903. }
  7904. // Tags
  7905. if (BABYLON.Tags) {
  7906. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7907. }
  7908. var classStore = getMergedStore(destination);
  7909. // Properties
  7910. for (var property in classStore) {
  7911. var propertyDescriptor = classStore[property];
  7912. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7913. var propertyType = propertyDescriptor.type;
  7914. if (sourceProperty !== undefined && sourceProperty !== null) {
  7915. var dest = destination;
  7916. switch (propertyType) {
  7917. case 0: // Value
  7918. dest[property] = sourceProperty;
  7919. break;
  7920. case 1: // Texture
  7921. if (scene) {
  7922. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7923. }
  7924. break;
  7925. case 2: // Color3
  7926. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7927. break;
  7928. case 3: // FresnelParameters
  7929. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7930. break;
  7931. case 4: // Vector2
  7932. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7933. break;
  7934. case 5: // Vector3
  7935. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7936. break;
  7937. case 6: // Mesh reference
  7938. if (scene) {
  7939. dest[property] = scene.getLastMeshByID(sourceProperty);
  7940. }
  7941. break;
  7942. case 7: // Color Curves
  7943. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7944. break;
  7945. case 8: // Color 4
  7946. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7947. break;
  7948. case 9: // Image Processing
  7949. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7950. break;
  7951. case 10: // Quaternion
  7952. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7953. break;
  7954. case 11: // Camera reference
  7955. if (scene) {
  7956. dest[property] = scene.getCameraByID(sourceProperty);
  7957. }
  7958. break;
  7959. }
  7960. }
  7961. }
  7962. return destination;
  7963. };
  7964. SerializationHelper.Clone = function (creationFunction, source) {
  7965. return _copySource(creationFunction, source, false);
  7966. };
  7967. SerializationHelper.Instanciate = function (creationFunction, source) {
  7968. return _copySource(creationFunction, source, true);
  7969. };
  7970. return SerializationHelper;
  7971. }());
  7972. BABYLON.SerializationHelper = SerializationHelper;
  7973. })(BABYLON || (BABYLON = {}));
  7974. //# sourceMappingURL=babylon.decorators.js.map
  7975. var BABYLON;
  7976. (function (BABYLON) {
  7977. /**
  7978. * Wrapper class for promise with external resolve and reject.
  7979. */
  7980. var Deferred = /** @class */ (function () {
  7981. /**
  7982. * Constructor for this deferred object.
  7983. */
  7984. function Deferred() {
  7985. var _this = this;
  7986. this.promise = new Promise(function (resolve, reject) {
  7987. _this._resolve = resolve;
  7988. _this._reject = reject;
  7989. });
  7990. }
  7991. Object.defineProperty(Deferred.prototype, "resolve", {
  7992. /**
  7993. * The resolve method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._resolve;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Deferred.prototype, "reject", {
  8002. /**
  8003. * The reject method of the promise associated with this deferred object.
  8004. */
  8005. get: function () {
  8006. return this._reject;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. return Deferred;
  8012. }());
  8013. BABYLON.Deferred = Deferred;
  8014. })(BABYLON || (BABYLON = {}));
  8015. //# sourceMappingURL=babylon.deferred.js.map
  8016. var BABYLON;
  8017. (function (BABYLON) {
  8018. /**
  8019. * A class serves as a medium between the observable and its observers
  8020. */
  8021. var EventState = /** @class */ (function () {
  8022. /**
  8023. * Create a new EventState
  8024. * @param mask defines the mask associated with this state
  8025. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8026. * @param target defines the original target of the state
  8027. * @param currentTarget defines the current target of the state
  8028. */
  8029. function EventState(mask, skipNextObservers, target, currentTarget) {
  8030. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8031. this.initalize(mask, skipNextObservers, target, currentTarget);
  8032. }
  8033. /**
  8034. * Initialize the current event state
  8035. * @param mask defines the mask associated with this state
  8036. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8037. * @param target defines the original target of the state
  8038. * @param currentTarget defines the current target of the state
  8039. * @returns the current event state
  8040. */
  8041. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8042. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8043. this.mask = mask;
  8044. this.skipNextObservers = skipNextObservers;
  8045. this.target = target;
  8046. this.currentTarget = currentTarget;
  8047. return this;
  8048. };
  8049. return EventState;
  8050. }());
  8051. BABYLON.EventState = EventState;
  8052. /**
  8053. * Represent an Observer registered to a given Observable object.
  8054. */
  8055. var Observer = /** @class */ (function () {
  8056. /**
  8057. * Creates a new observer
  8058. * @param callback defines the callback to call when the observer is notified
  8059. * @param mask defines the mask of the observer (used to filter notifications)
  8060. * @param scope defines the current scope used to restore the JS context
  8061. */
  8062. function Observer(
  8063. /**
  8064. * Defines the callback to call when the observer is notified
  8065. */
  8066. callback,
  8067. /**
  8068. * Defines the mask of the observer (used to filter notifications)
  8069. */
  8070. mask,
  8071. /**
  8072. * Defines the current scope used to restore the JS context
  8073. */
  8074. scope) {
  8075. if (scope === void 0) { scope = null; }
  8076. this.callback = callback;
  8077. this.mask = mask;
  8078. this.scope = scope;
  8079. /** @hidden */
  8080. this._willBeUnregistered = false;
  8081. /**
  8082. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8083. */
  8084. this.unregisterOnNextCall = false;
  8085. }
  8086. return Observer;
  8087. }());
  8088. BABYLON.Observer = Observer;
  8089. /**
  8090. * Represent a list of observers registered to multiple Observables object.
  8091. */
  8092. var MultiObserver = /** @class */ (function () {
  8093. function MultiObserver() {
  8094. }
  8095. /**
  8096. * Release associated resources
  8097. */
  8098. MultiObserver.prototype.dispose = function () {
  8099. if (this._observers && this._observables) {
  8100. for (var index = 0; index < this._observers.length; index++) {
  8101. this._observables[index].remove(this._observers[index]);
  8102. }
  8103. }
  8104. this._observers = null;
  8105. this._observables = null;
  8106. };
  8107. /**
  8108. * Raise a callback when one of the observable will notify
  8109. * @param observables defines a list of observables to watch
  8110. * @param callback defines the callback to call on notification
  8111. * @param mask defines the mask used to filter notifications
  8112. * @param scope defines the current scope used to restore the JS context
  8113. * @returns the new MultiObserver
  8114. */
  8115. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8116. if (mask === void 0) { mask = -1; }
  8117. if (scope === void 0) { scope = null; }
  8118. var result = new MultiObserver();
  8119. result._observers = new Array();
  8120. result._observables = observables;
  8121. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8122. var observable = observables_1[_i];
  8123. var observer = observable.add(callback, mask, false, scope);
  8124. if (observer) {
  8125. result._observers.push(observer);
  8126. }
  8127. }
  8128. return result;
  8129. };
  8130. return MultiObserver;
  8131. }());
  8132. BABYLON.MultiObserver = MultiObserver;
  8133. /**
  8134. * The Observable class is a simple implementation of the Observable pattern.
  8135. *
  8136. * 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.
  8137. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8138. * 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).
  8139. * 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.
  8140. */
  8141. var Observable = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observable
  8144. * @param onObserverAdded defines a callback to call when a new observer is added
  8145. */
  8146. function Observable(onObserverAdded) {
  8147. this._observers = new Array();
  8148. this._eventState = new EventState(0);
  8149. if (onObserverAdded) {
  8150. this._onObserverAdded = onObserverAdded;
  8151. }
  8152. }
  8153. /**
  8154. * Create a new Observer with the specified callback
  8155. * @param callback the callback that will be executed for that Observer
  8156. * @param mask the mask used to filter observers
  8157. * @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.
  8158. * @param scope optional scope for the callback to be called from
  8159. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8160. * @returns the new observer created for the callback
  8161. */
  8162. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8163. if (mask === void 0) { mask = -1; }
  8164. if (insertFirst === void 0) { insertFirst = false; }
  8165. if (scope === void 0) { scope = null; }
  8166. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8167. if (!callback) {
  8168. return null;
  8169. }
  8170. var observer = new Observer(callback, mask, scope);
  8171. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8172. if (insertFirst) {
  8173. this._observers.unshift(observer);
  8174. }
  8175. else {
  8176. this._observers.push(observer);
  8177. }
  8178. if (this._onObserverAdded) {
  8179. this._onObserverAdded(observer);
  8180. }
  8181. return observer;
  8182. };
  8183. /**
  8184. * Remove an Observer from the Observable object
  8185. * @param observer the instance of the Observer to remove
  8186. * @returns false if it doesn't belong to this Observable
  8187. */
  8188. Observable.prototype.remove = function (observer) {
  8189. if (!observer) {
  8190. return false;
  8191. }
  8192. var index = this._observers.indexOf(observer);
  8193. if (index !== -1) {
  8194. this._observers.splice(index, 1);
  8195. return true;
  8196. }
  8197. return false;
  8198. };
  8199. /**
  8200. * Remove a callback from the Observable object
  8201. * @param callback the callback to remove
  8202. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8203. * @returns false if it doesn't belong to this Observable
  8204. */
  8205. Observable.prototype.removeCallback = function (callback, scope) {
  8206. for (var index = 0; index < this._observers.length; index++) {
  8207. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8208. this._observers.splice(index, 1);
  8209. return true;
  8210. }
  8211. }
  8212. return false;
  8213. };
  8214. Observable.prototype._deferUnregister = function (observer) {
  8215. var _this = this;
  8216. observer.unregisterOnNextCall = false;
  8217. observer._willBeUnregistered = true;
  8218. BABYLON.Tools.SetImmediate(function () {
  8219. _this.remove(observer);
  8220. });
  8221. };
  8222. /**
  8223. * Notify all Observers by calling their respective callback with the given data
  8224. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8225. * @param eventData defines the data to send to all observers
  8226. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8227. * @param target defines the original target of the state
  8228. * @param currentTarget defines the current target of the state
  8229. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8230. */
  8231. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8232. if (mask === void 0) { mask = -1; }
  8233. if (!this._observers.length) {
  8234. return true;
  8235. }
  8236. var state = this._eventState;
  8237. state.mask = mask;
  8238. state.target = target;
  8239. state.currentTarget = currentTarget;
  8240. state.skipNextObservers = false;
  8241. state.lastReturnValue = eventData;
  8242. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8243. var obs = _a[_i];
  8244. if (obs._willBeUnregistered) {
  8245. continue;
  8246. }
  8247. if (obs.mask & mask) {
  8248. if (obs.scope) {
  8249. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8250. }
  8251. else {
  8252. state.lastReturnValue = obs.callback(eventData, state);
  8253. }
  8254. if (obs.unregisterOnNextCall) {
  8255. this._deferUnregister(obs);
  8256. }
  8257. }
  8258. if (state.skipNextObservers) {
  8259. return false;
  8260. }
  8261. }
  8262. return true;
  8263. };
  8264. /**
  8265. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8266. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8267. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8268. * and it is crucial that all callbacks will be executed.
  8269. * The order of the callbacks is kept, callbacks are not executed parallel.
  8270. *
  8271. * @param eventData The data to be sent to each callback
  8272. * @param mask is used to filter observers defaults to -1
  8273. * @param target defines the callback target (see EventState)
  8274. * @param currentTarget defines he current object in the bubbling phase
  8275. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8276. */
  8277. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8278. var _this = this;
  8279. if (mask === void 0) { mask = -1; }
  8280. // create an empty promise
  8281. var p = Promise.resolve(eventData);
  8282. // no observers? return this promise.
  8283. if (!this._observers.length) {
  8284. return p;
  8285. }
  8286. var state = this._eventState;
  8287. state.mask = mask;
  8288. state.target = target;
  8289. state.currentTarget = currentTarget;
  8290. state.skipNextObservers = false;
  8291. // execute one callback after another (not using Promise.all, the order is important)
  8292. this._observers.forEach(function (obs) {
  8293. if (state.skipNextObservers) {
  8294. return;
  8295. }
  8296. if (obs._willBeUnregistered) {
  8297. return;
  8298. }
  8299. if (obs.mask & mask) {
  8300. if (obs.scope) {
  8301. p = p.then(function (lastReturnedValue) {
  8302. state.lastReturnValue = lastReturnedValue;
  8303. return obs.callback.apply(obs.scope, [eventData, state]);
  8304. });
  8305. }
  8306. else {
  8307. p = p.then(function (lastReturnedValue) {
  8308. state.lastReturnValue = lastReturnedValue;
  8309. return obs.callback(eventData, state);
  8310. });
  8311. }
  8312. if (obs.unregisterOnNextCall) {
  8313. _this._deferUnregister(obs);
  8314. }
  8315. }
  8316. });
  8317. // return the eventData
  8318. return p.then(function () { return eventData; });
  8319. };
  8320. /**
  8321. * Notify a specific observer
  8322. * @param observer defines the observer to notify
  8323. * @param eventData defines the data to be sent to each callback
  8324. * @param mask is used to filter observers defaults to -1
  8325. */
  8326. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8327. if (mask === void 0) { mask = -1; }
  8328. var state = this._eventState;
  8329. state.mask = mask;
  8330. state.skipNextObservers = false;
  8331. observer.callback(eventData, state);
  8332. };
  8333. /**
  8334. * Gets a boolean indicating if the observable has at least one observer
  8335. * @returns true is the Observable has at least one Observer registered
  8336. */
  8337. Observable.prototype.hasObservers = function () {
  8338. return this._observers.length > 0;
  8339. };
  8340. /**
  8341. * Clear the list of observers
  8342. */
  8343. Observable.prototype.clear = function () {
  8344. this._observers = new Array();
  8345. this._onObserverAdded = null;
  8346. };
  8347. /**
  8348. * Clone the current observable
  8349. * @returns a new observable
  8350. */
  8351. Observable.prototype.clone = function () {
  8352. var result = new Observable();
  8353. result._observers = this._observers.slice(0);
  8354. return result;
  8355. };
  8356. /**
  8357. * Does this observable handles observer registered with a given mask
  8358. * @param mask defines the mask to be tested
  8359. * @return whether or not one observer registered with the given mask is handeled
  8360. **/
  8361. Observable.prototype.hasSpecificMask = function (mask) {
  8362. if (mask === void 0) { mask = -1; }
  8363. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8364. var obs = _a[_i];
  8365. if (obs.mask & mask || obs.mask === mask) {
  8366. return true;
  8367. }
  8368. }
  8369. return false;
  8370. };
  8371. return Observable;
  8372. }());
  8373. BABYLON.Observable = Observable;
  8374. })(BABYLON || (BABYLON = {}));
  8375. //# sourceMappingURL=babylon.observable.js.map
  8376. var BABYLON;
  8377. (function (BABYLON) {
  8378. var SmartArray = /** @class */ (function () {
  8379. function SmartArray(capacity) {
  8380. this.length = 0;
  8381. this.data = new Array(capacity);
  8382. this._id = SmartArray._GlobalId++;
  8383. }
  8384. SmartArray.prototype.push = function (value) {
  8385. this.data[this.length++] = value;
  8386. if (this.length > this.data.length) {
  8387. this.data.length *= 2;
  8388. }
  8389. };
  8390. SmartArray.prototype.forEach = function (func) {
  8391. for (var index = 0; index < this.length; index++) {
  8392. func(this.data[index]);
  8393. }
  8394. };
  8395. SmartArray.prototype.sort = function (compareFn) {
  8396. this.data.sort(compareFn);
  8397. };
  8398. SmartArray.prototype.reset = function () {
  8399. this.length = 0;
  8400. };
  8401. SmartArray.prototype.dispose = function () {
  8402. this.reset();
  8403. if (this.data) {
  8404. this.data.length = 0;
  8405. this.data = [];
  8406. }
  8407. };
  8408. SmartArray.prototype.concat = function (array) {
  8409. if (array.length === 0) {
  8410. return;
  8411. }
  8412. if (this.length + array.length > this.data.length) {
  8413. this.data.length = (this.length + array.length) * 2;
  8414. }
  8415. for (var index = 0; index < array.length; index++) {
  8416. this.data[this.length++] = (array.data || array)[index];
  8417. }
  8418. };
  8419. SmartArray.prototype.indexOf = function (value) {
  8420. var position = this.data.indexOf(value);
  8421. if (position >= this.length) {
  8422. return -1;
  8423. }
  8424. return position;
  8425. };
  8426. SmartArray.prototype.contains = function (value) {
  8427. return this.data.indexOf(value) !== -1;
  8428. };
  8429. // Statics
  8430. SmartArray._GlobalId = 0;
  8431. return SmartArray;
  8432. }());
  8433. BABYLON.SmartArray = SmartArray;
  8434. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8435. __extends(SmartArrayNoDuplicate, _super);
  8436. function SmartArrayNoDuplicate() {
  8437. var _this = _super !== null && _super.apply(this, arguments) || this;
  8438. _this._duplicateId = 0;
  8439. return _this;
  8440. }
  8441. SmartArrayNoDuplicate.prototype.push = function (value) {
  8442. _super.prototype.push.call(this, value);
  8443. if (!value.__smartArrayFlags) {
  8444. value.__smartArrayFlags = {};
  8445. }
  8446. value.__smartArrayFlags[this._id] = this._duplicateId;
  8447. };
  8448. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8449. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8450. return false;
  8451. }
  8452. this.push(value);
  8453. return true;
  8454. };
  8455. SmartArrayNoDuplicate.prototype.reset = function () {
  8456. _super.prototype.reset.call(this);
  8457. this._duplicateId++;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8460. if (array.length === 0) {
  8461. return;
  8462. }
  8463. if (this.length + array.length > this.data.length) {
  8464. this.data.length = (this.length + array.length) * 2;
  8465. }
  8466. for (var index = 0; index < array.length; index++) {
  8467. var item = (array.data || array)[index];
  8468. this.pushNoDuplicate(item);
  8469. }
  8470. };
  8471. return SmartArrayNoDuplicate;
  8472. }(SmartArray));
  8473. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8474. })(BABYLON || (BABYLON = {}));
  8475. //# sourceMappingURL=babylon.smartArray.js.map
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8479. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8480. var LoadFileError = /** @class */ (function (_super) {
  8481. __extends(LoadFileError, _super);
  8482. function LoadFileError(message, request) {
  8483. var _this = _super.call(this, message) || this;
  8484. _this.request = request;
  8485. _this.name = "LoadFileError";
  8486. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8487. return _this;
  8488. }
  8489. // Polyfill for Object.setPrototypeOf if necessary.
  8490. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8491. return LoadFileError;
  8492. }(Error));
  8493. BABYLON.LoadFileError = LoadFileError;
  8494. var RetryStrategy = /** @class */ (function () {
  8495. function RetryStrategy() {
  8496. }
  8497. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8498. if (maxRetries === void 0) { maxRetries = 3; }
  8499. if (baseInterval === void 0) { baseInterval = 500; }
  8500. return function (url, request, retryIndex) {
  8501. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8502. return -1;
  8503. }
  8504. return Math.pow(2, retryIndex) * baseInterval;
  8505. };
  8506. };
  8507. return RetryStrategy;
  8508. }());
  8509. BABYLON.RetryStrategy = RetryStrategy;
  8510. // Screenshots
  8511. var screenshotCanvas;
  8512. var cloneValue = function (source, destinationObject) {
  8513. if (!source)
  8514. return null;
  8515. if (source instanceof BABYLON.Mesh) {
  8516. return null;
  8517. }
  8518. if (source instanceof BABYLON.SubMesh) {
  8519. return source.clone(destinationObject);
  8520. }
  8521. else if (source.clone) {
  8522. return source.clone();
  8523. }
  8524. return null;
  8525. };
  8526. var Tools = /** @class */ (function () {
  8527. function Tools() {
  8528. }
  8529. /**
  8530. * Interpolates between a and b via alpha
  8531. * @param a The lower value (returned when alpha = 0)
  8532. * @param b The upper value (returned when alpha = 1)
  8533. * @param alpha The interpolation-factor
  8534. * @return The mixed value
  8535. */
  8536. Tools.Mix = function (a, b, alpha) {
  8537. return a * (1 - alpha) + b * alpha;
  8538. };
  8539. Tools.Instantiate = function (className) {
  8540. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8541. return Tools.RegisteredExternalClasses[className];
  8542. }
  8543. var arr = className.split(".");
  8544. var fn = (window || this);
  8545. for (var i = 0, len = arr.length; i < len; i++) {
  8546. fn = fn[arr[i]];
  8547. }
  8548. if (typeof fn !== "function") {
  8549. return null;
  8550. }
  8551. return fn;
  8552. };
  8553. /**
  8554. * Provides a slice function that will work even on IE
  8555. * @param data defines the array to slice
  8556. * @param start defines the start of the data (optional)
  8557. * @param end defines the end of the data (optional)
  8558. * @returns the new sliced array
  8559. */
  8560. Tools.Slice = function (data, start, end) {
  8561. if (data.slice) {
  8562. return data.slice(start, end);
  8563. }
  8564. return Array.prototype.slice.call(data, start, end);
  8565. };
  8566. Tools.SetImmediate = function (action) {
  8567. if (window.setImmediate) {
  8568. window.setImmediate(action);
  8569. }
  8570. else {
  8571. setTimeout(action, 1);
  8572. }
  8573. };
  8574. Tools.IsExponentOfTwo = function (value) {
  8575. var count = 1;
  8576. do {
  8577. count *= 2;
  8578. } while (count < value);
  8579. return count === value;
  8580. };
  8581. /**
  8582. * Returns the nearest 32-bit single precision float representation of a Number
  8583. * @param value A Number. If the parameter is of a different type, it will get converted
  8584. * to a number or to NaN if it cannot be converted
  8585. * @returns number
  8586. */
  8587. Tools.FloatRound = function (value) {
  8588. if (Math.fround) {
  8589. return Math.fround(value);
  8590. }
  8591. return (Tools._tmpFloatArray[0] = value);
  8592. };
  8593. /**
  8594. * Find the next highest power of two.
  8595. * @param x Number to start search from.
  8596. * @return Next highest power of two.
  8597. */
  8598. Tools.CeilingPOT = function (x) {
  8599. x--;
  8600. x |= x >> 1;
  8601. x |= x >> 2;
  8602. x |= x >> 4;
  8603. x |= x >> 8;
  8604. x |= x >> 16;
  8605. x++;
  8606. return x;
  8607. };
  8608. /**
  8609. * Find the next lowest power of two.
  8610. * @param x Number to start search from.
  8611. * @return Next lowest power of two.
  8612. */
  8613. Tools.FloorPOT = function (x) {
  8614. x = x | (x >> 1);
  8615. x = x | (x >> 2);
  8616. x = x | (x >> 4);
  8617. x = x | (x >> 8);
  8618. x = x | (x >> 16);
  8619. return x - (x >> 1);
  8620. };
  8621. /**
  8622. * Find the nearest power of two.
  8623. * @param x Number to start search from.
  8624. * @return Next nearest power of two.
  8625. */
  8626. Tools.NearestPOT = function (x) {
  8627. var c = Tools.CeilingPOT(x);
  8628. var f = Tools.FloorPOT(x);
  8629. return (c - x) > (x - f) ? f : c;
  8630. };
  8631. Tools.GetExponentOfTwo = function (value, max, mode) {
  8632. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8633. var pot;
  8634. switch (mode) {
  8635. case BABYLON.Engine.SCALEMODE_FLOOR:
  8636. pot = Tools.FloorPOT(value);
  8637. break;
  8638. case BABYLON.Engine.SCALEMODE_NEAREST:
  8639. pot = Tools.NearestPOT(value);
  8640. break;
  8641. case BABYLON.Engine.SCALEMODE_CEILING:
  8642. default:
  8643. pot = Tools.CeilingPOT(value);
  8644. break;
  8645. }
  8646. return Math.min(pot, max);
  8647. };
  8648. Tools.GetFilename = function (path) {
  8649. var index = path.lastIndexOf("/");
  8650. if (index < 0)
  8651. return path;
  8652. return path.substring(index + 1);
  8653. };
  8654. /**
  8655. * Extracts the "folder" part of a path (everything before the filename).
  8656. * @param uri The URI to extract the info from
  8657. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8658. * @returns The "folder" part of the path
  8659. */
  8660. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8661. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8662. var index = uri.lastIndexOf("/");
  8663. if (index < 0) {
  8664. if (returnUnchangedIfNoSlash) {
  8665. return uri;
  8666. }
  8667. return "";
  8668. }
  8669. return uri.substring(0, index + 1);
  8670. };
  8671. Tools.GetDOMTextContent = function (element) {
  8672. var result = "";
  8673. var child = element.firstChild;
  8674. while (child) {
  8675. if (child.nodeType === 3) {
  8676. result += child.textContent;
  8677. }
  8678. child = child.nextSibling;
  8679. }
  8680. return result;
  8681. };
  8682. Tools.ToDegrees = function (angle) {
  8683. return angle * 180 / Math.PI;
  8684. };
  8685. Tools.ToRadians = function (angle) {
  8686. return angle * Math.PI / 180;
  8687. };
  8688. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8689. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8690. var output = "";
  8691. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8692. var i = 0;
  8693. var bytes = new Uint8Array(buffer);
  8694. while (i < bytes.length) {
  8695. chr1 = bytes[i++];
  8696. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8697. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8698. enc1 = chr1 >> 2;
  8699. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8700. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8701. enc4 = chr3 & 63;
  8702. if (isNaN(chr2)) {
  8703. enc3 = enc4 = 64;
  8704. }
  8705. else if (isNaN(chr3)) {
  8706. enc4 = 64;
  8707. }
  8708. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8709. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8710. }
  8711. return "data:image/png;base64," + output;
  8712. };
  8713. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8714. if (bias === void 0) { bias = null; }
  8715. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8716. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8717. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8718. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8719. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8720. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8721. }
  8722. if (bias) {
  8723. minimum.x -= minimum.x * bias.x + bias.y;
  8724. minimum.y -= minimum.y * bias.x + bias.y;
  8725. minimum.z -= minimum.z * bias.x + bias.y;
  8726. maximum.x += maximum.x * bias.x + bias.y;
  8727. maximum.y += maximum.y * bias.x + bias.y;
  8728. maximum.z += maximum.z * bias.x + bias.y;
  8729. }
  8730. return {
  8731. minimum: minimum,
  8732. maximum: maximum
  8733. };
  8734. };
  8735. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8736. if (bias === void 0) { bias = null; }
  8737. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8738. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8739. if (!stride) {
  8740. stride = 3;
  8741. }
  8742. for (var index = start; index < start + count; index++) {
  8743. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8744. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8745. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8746. }
  8747. if (bias) {
  8748. minimum.x -= minimum.x * bias.x + bias.y;
  8749. minimum.y -= minimum.y * bias.x + bias.y;
  8750. minimum.z -= minimum.z * bias.x + bias.y;
  8751. maximum.x += maximum.x * bias.x + bias.y;
  8752. maximum.y += maximum.y * bias.x + bias.y;
  8753. maximum.z += maximum.z * bias.x + bias.y;
  8754. }
  8755. return {
  8756. minimum: minimum,
  8757. maximum: maximum
  8758. };
  8759. };
  8760. Tools.Vector2ArrayFeeder = function (array) {
  8761. return function (index) {
  8762. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8763. var length = isFloatArray ? array.length / 2 : array.length;
  8764. if (index >= length) {
  8765. return null;
  8766. }
  8767. if (isFloatArray) {
  8768. var fa = array;
  8769. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8770. }
  8771. var a = array;
  8772. return a[index];
  8773. };
  8774. };
  8775. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8776. if (bias === void 0) { bias = null; }
  8777. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8778. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8779. var i = 0;
  8780. var cur = feeder(i++);
  8781. while (cur) {
  8782. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8783. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8784. cur = feeder(i++);
  8785. }
  8786. if (bias) {
  8787. minimum.x -= minimum.x * bias.x + bias.y;
  8788. minimum.y -= minimum.y * bias.x + bias.y;
  8789. maximum.x += maximum.x * bias.x + bias.y;
  8790. maximum.y += maximum.y * bias.x + bias.y;
  8791. }
  8792. return {
  8793. minimum: minimum,
  8794. maximum: maximum
  8795. };
  8796. };
  8797. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8798. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8799. return null;
  8800. return Array.isArray(obj) ? obj : [obj];
  8801. };
  8802. // Misc.
  8803. Tools.GetPointerPrefix = function () {
  8804. var eventPrefix = "pointer";
  8805. // Check if pointer events are supported
  8806. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8807. eventPrefix = "mouse";
  8808. }
  8809. return eventPrefix;
  8810. };
  8811. /**
  8812. * @param func - the function to be called
  8813. * @param requester - the object that will request the next frame. Falls back to window.
  8814. */
  8815. Tools.QueueNewFrame = function (func, requester) {
  8816. if (!Tools.IsWindowObjectExist()) {
  8817. return setTimeout(func, 16);
  8818. }
  8819. if (!requester) {
  8820. requester = window;
  8821. }
  8822. if (requester.requestAnimationFrame) {
  8823. return requester.requestAnimationFrame(func);
  8824. }
  8825. else if (requester.msRequestAnimationFrame) {
  8826. return requester.msRequestAnimationFrame(func);
  8827. }
  8828. else if (requester.webkitRequestAnimationFrame) {
  8829. return requester.webkitRequestAnimationFrame(func);
  8830. }
  8831. else if (requester.mozRequestAnimationFrame) {
  8832. return requester.mozRequestAnimationFrame(func);
  8833. }
  8834. else if (requester.oRequestAnimationFrame) {
  8835. return requester.oRequestAnimationFrame(func);
  8836. }
  8837. else {
  8838. return window.setTimeout(func, 16);
  8839. }
  8840. };
  8841. Tools.RequestFullscreen = function (element) {
  8842. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8843. if (!requestFunction)
  8844. return;
  8845. requestFunction.call(element);
  8846. };
  8847. Tools.ExitFullscreen = function () {
  8848. if (document.exitFullscreen) {
  8849. document.exitFullscreen();
  8850. }
  8851. else if (document.mozCancelFullScreen) {
  8852. document.mozCancelFullScreen();
  8853. }
  8854. else if (document.webkitCancelFullScreen) {
  8855. document.webkitCancelFullScreen();
  8856. }
  8857. else if (document.msCancelFullScreen) {
  8858. document.msCancelFullScreen();
  8859. }
  8860. };
  8861. Tools.SetCorsBehavior = function (url, element) {
  8862. if (url && url.indexOf("data:") === 0) {
  8863. return;
  8864. }
  8865. if (Tools.CorsBehavior) {
  8866. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8867. element.crossOrigin = Tools.CorsBehavior;
  8868. }
  8869. else {
  8870. var result = Tools.CorsBehavior(url);
  8871. if (result) {
  8872. element.crossOrigin = result;
  8873. }
  8874. }
  8875. }
  8876. };
  8877. // External files
  8878. Tools.CleanUrl = function (url) {
  8879. url = url.replace(/#/mg, "%23");
  8880. return url;
  8881. };
  8882. /**
  8883. * Loads an image as an HTMLImageElement.
  8884. * @param input url string, ArrayBuffer, or Blob to load
  8885. * @param onLoad callback called when the image successfully loads
  8886. * @param onError callback called when the image fails to load
  8887. * @param database database for caching
  8888. * @returns the HTMLImageElement of the loaded image
  8889. */
  8890. Tools.LoadImage = function (input, onLoad, onError, database) {
  8891. var url;
  8892. var usingObjectURL = false;
  8893. if (input instanceof ArrayBuffer) {
  8894. url = URL.createObjectURL(new Blob([input]));
  8895. usingObjectURL = true;
  8896. }
  8897. else if (input instanceof Blob) {
  8898. url = URL.createObjectURL(input);
  8899. usingObjectURL = true;
  8900. }
  8901. else {
  8902. url = Tools.CleanUrl(input);
  8903. url = Tools.PreprocessUrl(input);
  8904. }
  8905. var img = new Image();
  8906. Tools.SetCorsBehavior(url, img);
  8907. var loadHandler = function () {
  8908. if (usingObjectURL && img.src) {
  8909. URL.revokeObjectURL(img.src);
  8910. }
  8911. img.removeEventListener("load", loadHandler);
  8912. img.removeEventListener("error", errorHandler);
  8913. onLoad(img);
  8914. };
  8915. var errorHandler = function (err) {
  8916. if (usingObjectURL && img.src) {
  8917. URL.revokeObjectURL(img.src);
  8918. }
  8919. img.removeEventListener("load", loadHandler);
  8920. img.removeEventListener("error", errorHandler);
  8921. Tools.Error("Error while trying to load image: " + input);
  8922. if (onError) {
  8923. onError("Error while trying to load image: " + input, err);
  8924. }
  8925. };
  8926. img.addEventListener("load", loadHandler);
  8927. img.addEventListener("error", errorHandler);
  8928. var noIndexedDB = function () {
  8929. img.src = url;
  8930. };
  8931. var loadFromIndexedDB = function () {
  8932. if (database) {
  8933. database.loadImageFromDB(url, img);
  8934. }
  8935. };
  8936. //ANY database to do!
  8937. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8938. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8939. }
  8940. else {
  8941. if (url.indexOf("file:") !== -1) {
  8942. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8943. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8944. try {
  8945. var blobURL;
  8946. try {
  8947. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8948. }
  8949. catch (ex) {
  8950. // Chrome doesn't support oneTimeOnly parameter
  8951. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8952. }
  8953. img.src = blobURL;
  8954. usingObjectURL = true;
  8955. }
  8956. catch (e) {
  8957. img.src = "";
  8958. }
  8959. return img;
  8960. }
  8961. }
  8962. noIndexedDB();
  8963. }
  8964. return img;
  8965. };
  8966. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8967. url = Tools.CleanUrl(url);
  8968. url = Tools.PreprocessUrl(url);
  8969. // If file and file input are set
  8970. if (url.indexOf("file:") !== -1) {
  8971. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8972. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8973. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8974. }
  8975. }
  8976. var loadUrl = Tools.BaseUrl + url;
  8977. var aborted = false;
  8978. var fileRequest = {
  8979. onCompleteObservable: new BABYLON.Observable(),
  8980. abort: function () { return aborted = true; },
  8981. };
  8982. var requestFile = function () {
  8983. var request = new XMLHttpRequest();
  8984. var retryHandle = null;
  8985. fileRequest.abort = function () {
  8986. aborted = true;
  8987. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8988. request.abort();
  8989. }
  8990. if (retryHandle !== null) {
  8991. clearTimeout(retryHandle);
  8992. retryHandle = null;
  8993. }
  8994. };
  8995. var retryLoop = function (retryIndex) {
  8996. request.open('GET', loadUrl, true);
  8997. if (useArrayBuffer) {
  8998. request.responseType = "arraybuffer";
  8999. }
  9000. if (onProgress) {
  9001. request.addEventListener("progress", onProgress);
  9002. }
  9003. var onLoadEnd = function () {
  9004. request.removeEventListener("loadend", onLoadEnd);
  9005. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9006. fileRequest.onCompleteObservable.clear();
  9007. };
  9008. request.addEventListener("loadend", onLoadEnd);
  9009. var onReadyStateChange = function () {
  9010. if (aborted) {
  9011. return;
  9012. }
  9013. // In case of undefined state in some browsers.
  9014. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9015. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9016. request.removeEventListener("readystatechange", onReadyStateChange);
  9017. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9018. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9019. return;
  9020. }
  9021. var retryStrategy = Tools.DefaultRetryStrategy;
  9022. if (retryStrategy) {
  9023. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9024. if (waitTime !== -1) {
  9025. // Prevent the request from completing for retry.
  9026. request.removeEventListener("loadend", onLoadEnd);
  9027. request = new XMLHttpRequest();
  9028. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9029. return;
  9030. }
  9031. }
  9032. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9033. if (onError) {
  9034. onError(request, e);
  9035. }
  9036. else {
  9037. throw e;
  9038. }
  9039. }
  9040. };
  9041. request.addEventListener("readystatechange", onReadyStateChange);
  9042. request.send();
  9043. };
  9044. retryLoop(0);
  9045. };
  9046. // Caching all files
  9047. if (database && database.enableSceneOffline) {
  9048. var noIndexedDB_1 = function () {
  9049. if (!aborted) {
  9050. requestFile();
  9051. }
  9052. };
  9053. var loadFromIndexedDB = function () {
  9054. // TODO: database needs to support aborting and should return a IFileRequest
  9055. if (aborted) {
  9056. return;
  9057. }
  9058. if (database) {
  9059. database.loadFileFromDB(url, function (data) {
  9060. if (!aborted) {
  9061. onSuccess(data);
  9062. }
  9063. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9064. }, onProgress ? function (event) {
  9065. if (!aborted) {
  9066. onProgress(event);
  9067. }
  9068. } : undefined, noIndexedDB_1, useArrayBuffer);
  9069. }
  9070. };
  9071. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9072. }
  9073. else {
  9074. requestFile();
  9075. }
  9076. return fileRequest;
  9077. };
  9078. /**
  9079. * Load a script (identified by an url). When the url returns, the
  9080. * content of this file is added into a new script element, attached to the DOM (body element)
  9081. */
  9082. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9083. var head = document.getElementsByTagName('head')[0];
  9084. var script = document.createElement('script');
  9085. script.type = 'text/javascript';
  9086. script.src = scriptUrl;
  9087. script.onload = function () {
  9088. if (onSuccess) {
  9089. onSuccess();
  9090. }
  9091. };
  9092. script.onerror = function (e) {
  9093. if (onError) {
  9094. onError("Unable to load script '" + scriptUrl + "'", e);
  9095. }
  9096. };
  9097. head.appendChild(script);
  9098. };
  9099. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9100. var reader = new FileReader();
  9101. var request = {
  9102. onCompleteObservable: new BABYLON.Observable(),
  9103. abort: function () { return reader.abort(); },
  9104. };
  9105. reader.onloadend = function (e) {
  9106. request.onCompleteObservable.notifyObservers(request);
  9107. };
  9108. reader.onload = function (e) {
  9109. //target doesn't have result from ts 1.3
  9110. callback(e.target['result']);
  9111. };
  9112. reader.onprogress = progressCallback;
  9113. reader.readAsDataURL(fileToLoad);
  9114. return request;
  9115. };
  9116. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9117. var reader = new FileReader();
  9118. var request = {
  9119. onCompleteObservable: new BABYLON.Observable(),
  9120. abort: function () { return reader.abort(); },
  9121. };
  9122. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9123. reader.onerror = function (e) {
  9124. Tools.Log("Error while reading file: " + fileToLoad.name);
  9125. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9126. };
  9127. reader.onload = function (e) {
  9128. //target doesn't have result from ts 1.3
  9129. callback(e.target['result']);
  9130. };
  9131. if (progressCallBack) {
  9132. reader.onprogress = progressCallBack;
  9133. }
  9134. if (!useArrayBuffer) {
  9135. // Asynchronous read
  9136. reader.readAsText(fileToLoad);
  9137. }
  9138. else {
  9139. reader.readAsArrayBuffer(fileToLoad);
  9140. }
  9141. return request;
  9142. };
  9143. //returns a downloadable url to a file content.
  9144. Tools.FileAsURL = function (content) {
  9145. var fileBlob = new Blob([content]);
  9146. var url = window.URL || window.webkitURL;
  9147. var link = url.createObjectURL(fileBlob);
  9148. return link;
  9149. };
  9150. // Misc.
  9151. Tools.Format = function (value, decimals) {
  9152. if (decimals === void 0) { decimals = 2; }
  9153. return value.toFixed(decimals);
  9154. };
  9155. Tools.CheckExtends = function (v, min, max) {
  9156. if (v.x < min.x)
  9157. min.x = v.x;
  9158. if (v.y < min.y)
  9159. min.y = v.y;
  9160. if (v.z < min.z)
  9161. min.z = v.z;
  9162. if (v.x > max.x)
  9163. max.x = v.x;
  9164. if (v.y > max.y)
  9165. max.y = v.y;
  9166. if (v.z > max.z)
  9167. max.z = v.z;
  9168. };
  9169. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9170. for (var prop in source) {
  9171. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9172. continue;
  9173. }
  9174. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9175. continue;
  9176. }
  9177. var sourceValue = source[prop];
  9178. var typeOfSourceValue = typeof sourceValue;
  9179. if (typeOfSourceValue === "function") {
  9180. continue;
  9181. }
  9182. try {
  9183. if (typeOfSourceValue === "object") {
  9184. if (sourceValue instanceof Array) {
  9185. destination[prop] = [];
  9186. if (sourceValue.length > 0) {
  9187. if (typeof sourceValue[0] == "object") {
  9188. for (var index = 0; index < sourceValue.length; index++) {
  9189. var clonedValue = cloneValue(sourceValue[index], destination);
  9190. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9191. destination[prop].push(clonedValue);
  9192. }
  9193. }
  9194. }
  9195. else {
  9196. destination[prop] = sourceValue.slice(0);
  9197. }
  9198. }
  9199. }
  9200. else {
  9201. destination[prop] = cloneValue(sourceValue, destination);
  9202. }
  9203. }
  9204. else {
  9205. destination[prop] = sourceValue;
  9206. }
  9207. }
  9208. catch (e) {
  9209. // Just ignore error (it could be because of a read-only property)
  9210. }
  9211. }
  9212. };
  9213. Tools.IsEmpty = function (obj) {
  9214. for (var i in obj) {
  9215. if (obj.hasOwnProperty(i)) {
  9216. return false;
  9217. }
  9218. }
  9219. return true;
  9220. };
  9221. Tools.RegisterTopRootEvents = function (events) {
  9222. for (var index = 0; index < events.length; index++) {
  9223. var event = events[index];
  9224. window.addEventListener(event.name, event.handler, false);
  9225. try {
  9226. if (window.parent) {
  9227. window.parent.addEventListener(event.name, event.handler, false);
  9228. }
  9229. }
  9230. catch (e) {
  9231. // Silently fails...
  9232. }
  9233. }
  9234. };
  9235. Tools.UnregisterTopRootEvents = function (events) {
  9236. for (var index = 0; index < events.length; index++) {
  9237. var event = events[index];
  9238. window.removeEventListener(event.name, event.handler);
  9239. try {
  9240. if (window.parent) {
  9241. window.parent.removeEventListener(event.name, event.handler);
  9242. }
  9243. }
  9244. catch (e) {
  9245. // Silently fails...
  9246. }
  9247. }
  9248. };
  9249. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9250. if (mimeType === void 0) { mimeType = "image/png"; }
  9251. // Read the contents of the framebuffer
  9252. var numberOfChannelsByLine = width * 4;
  9253. var halfHeight = height / 2;
  9254. //Reading datas from WebGL
  9255. var data = engine.readPixels(0, 0, width, height);
  9256. //To flip image on Y axis.
  9257. for (var i = 0; i < halfHeight; i++) {
  9258. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9259. var currentCell = j + i * numberOfChannelsByLine;
  9260. var targetLine = height - i - 1;
  9261. var targetCell = j + targetLine * numberOfChannelsByLine;
  9262. var temp = data[currentCell];
  9263. data[currentCell] = data[targetCell];
  9264. data[targetCell] = temp;
  9265. }
  9266. }
  9267. // Create a 2D canvas to store the result
  9268. if (!screenshotCanvas) {
  9269. screenshotCanvas = document.createElement('canvas');
  9270. }
  9271. screenshotCanvas.width = width;
  9272. screenshotCanvas.height = height;
  9273. var context = screenshotCanvas.getContext('2d');
  9274. if (context) {
  9275. // Copy the pixels to a 2D canvas
  9276. var imageData = context.createImageData(width, height);
  9277. var castData = (imageData.data);
  9278. castData.set(data);
  9279. context.putImageData(imageData, 0, 0);
  9280. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9281. }
  9282. };
  9283. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9284. if (mimeType === void 0) { mimeType = "image/png"; }
  9285. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9286. if (successCallback) {
  9287. successCallback(base64Image);
  9288. }
  9289. else {
  9290. // We need HTMLCanvasElement.toBlob for HD screenshots
  9291. if (!screenshotCanvas.toBlob) {
  9292. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9293. screenshotCanvas.toBlob = function (callback, type, quality) {
  9294. var _this = this;
  9295. setTimeout(function () {
  9296. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9297. for (var i = 0; i < len; i++) {
  9298. arr[i] = binStr.charCodeAt(i);
  9299. }
  9300. callback(new Blob([arr], { type: type || 'image/png' }));
  9301. });
  9302. };
  9303. }
  9304. screenshotCanvas.toBlob(function (blob) {
  9305. var url = URL.createObjectURL(blob);
  9306. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9307. if (("download" in document.createElement("a"))) {
  9308. var a = window.document.createElement("a");
  9309. a.href = url;
  9310. if (fileName) {
  9311. a.setAttribute("download", fileName);
  9312. }
  9313. else {
  9314. var date = new Date();
  9315. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9316. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9317. }
  9318. window.document.body.appendChild(a);
  9319. a.addEventListener("click", function () {
  9320. if (a.parentElement) {
  9321. a.parentElement.removeChild(a);
  9322. }
  9323. });
  9324. a.click();
  9325. }
  9326. else {
  9327. var newWindow = window.open("");
  9328. if (!newWindow)
  9329. return;
  9330. var img = newWindow.document.createElement("img");
  9331. img.onload = function () {
  9332. // no longer need to read the blob so it's revoked
  9333. URL.revokeObjectURL(url);
  9334. };
  9335. img.src = url;
  9336. newWindow.document.body.appendChild(img);
  9337. }
  9338. });
  9339. }
  9340. };
  9341. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9342. if (mimeType === void 0) { mimeType = "image/png"; }
  9343. var width;
  9344. var height;
  9345. // If a precision value is specified
  9346. if (size.precision) {
  9347. width = Math.round(engine.getRenderWidth() * size.precision);
  9348. height = Math.round(width / engine.getAspectRatio(camera));
  9349. }
  9350. else if (size.width && size.height) {
  9351. width = size.width;
  9352. height = size.height;
  9353. }
  9354. //If passing only width, computing height to keep display canvas ratio.
  9355. else if (size.width && !size.height) {
  9356. width = size.width;
  9357. height = Math.round(width / engine.getAspectRatio(camera));
  9358. }
  9359. //If passing only height, computing width to keep display canvas ratio.
  9360. else if (size.height && !size.width) {
  9361. height = size.height;
  9362. width = Math.round(height * engine.getAspectRatio(camera));
  9363. }
  9364. //Assuming here that "size" parameter is a number
  9365. else if (!isNaN(size)) {
  9366. height = size;
  9367. width = size;
  9368. }
  9369. else {
  9370. Tools.Error("Invalid 'size' parameter !");
  9371. return;
  9372. }
  9373. if (!screenshotCanvas) {
  9374. screenshotCanvas = document.createElement('canvas');
  9375. }
  9376. screenshotCanvas.width = width;
  9377. screenshotCanvas.height = height;
  9378. var renderContext = screenshotCanvas.getContext("2d");
  9379. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9380. var newWidth = width;
  9381. var newHeight = newWidth / ratio;
  9382. if (newHeight > height) {
  9383. newHeight = height;
  9384. newWidth = newHeight * ratio;
  9385. }
  9386. var offsetX = Math.max(0, width - newWidth) / 2;
  9387. var offsetY = Math.max(0, height - newHeight) / 2;
  9388. var renderingCanvas = engine.getRenderingCanvas();
  9389. if (renderContext && renderingCanvas) {
  9390. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9391. }
  9392. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9393. };
  9394. /**
  9395. * Generates an image screenshot from the specified camera.
  9396. *
  9397. * @param engine The engine to use for rendering
  9398. * @param camera The camera to use for rendering
  9399. * @param size This parameter can be set to a single number or to an object with the
  9400. * following (optional) properties: precision, width, height. If a single number is passed,
  9401. * it will be used for both width and height. If an object is passed, the screenshot size
  9402. * will be derived from the parameters. The precision property is a multiplier allowing
  9403. * rendering at a higher or lower resolution.
  9404. * @param successCallback The callback receives a single parameter which contains the
  9405. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9406. * src parameter of an <img> to display it.
  9407. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9408. * Check your browser for supported MIME types.
  9409. * @param samples Texture samples (default: 1)
  9410. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9411. * @param fileName A name for for the downloaded file.
  9412. * @constructor
  9413. */
  9414. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9415. if (mimeType === void 0) { mimeType = "image/png"; }
  9416. if (samples === void 0) { samples = 1; }
  9417. if (antialiasing === void 0) { antialiasing = false; }
  9418. var width;
  9419. var height;
  9420. //If a precision value is specified
  9421. if (size.precision) {
  9422. width = Math.round(engine.getRenderWidth() * size.precision);
  9423. height = Math.round(width / engine.getAspectRatio(camera));
  9424. size = { width: width, height: height };
  9425. }
  9426. else if (size.width && size.height) {
  9427. width = size.width;
  9428. height = size.height;
  9429. }
  9430. //If passing only width, computing height to keep display canvas ratio.
  9431. else if (size.width && !size.height) {
  9432. width = size.width;
  9433. height = Math.round(width / engine.getAspectRatio(camera));
  9434. size = { width: width, height: height };
  9435. }
  9436. //If passing only height, computing width to keep display canvas ratio.
  9437. else if (size.height && !size.width) {
  9438. height = size.height;
  9439. width = Math.round(height * engine.getAspectRatio(camera));
  9440. size = { width: width, height: height };
  9441. }
  9442. //Assuming here that "size" parameter is a number
  9443. else if (!isNaN(size)) {
  9444. height = size;
  9445. width = size;
  9446. }
  9447. else {
  9448. Tools.Error("Invalid 'size' parameter !");
  9449. return;
  9450. }
  9451. var scene = camera.getScene();
  9452. var previousCamera = null;
  9453. if (scene.activeCamera !== camera) {
  9454. previousCamera = scene.activeCamera;
  9455. scene.activeCamera = camera;
  9456. }
  9457. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9458. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9459. texture.renderList = null;
  9460. texture.samples = samples;
  9461. if (antialiasing) {
  9462. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9463. }
  9464. texture.onAfterRenderObservable.add(function () {
  9465. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9466. });
  9467. scene.incrementRenderId();
  9468. scene.resetCachedMaterial();
  9469. texture.render(true);
  9470. texture.dispose();
  9471. if (previousCamera) {
  9472. scene.activeCamera = previousCamera;
  9473. }
  9474. camera.getProjectionMatrix(true); // Force cache refresh;
  9475. };
  9476. // XHR response validator for local file scenario
  9477. Tools.ValidateXHRData = function (xhr, dataType) {
  9478. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9479. if (dataType === void 0) { dataType = 7; }
  9480. try {
  9481. if (dataType & 1) {
  9482. if (xhr.responseText && xhr.responseText.length > 0) {
  9483. return true;
  9484. }
  9485. else if (dataType === 1) {
  9486. return false;
  9487. }
  9488. }
  9489. if (dataType & 2) {
  9490. // Check header width and height since there is no "TGA" magic number
  9491. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9492. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9493. return true;
  9494. }
  9495. else if (dataType === 2) {
  9496. return false;
  9497. }
  9498. }
  9499. if (dataType & 4) {
  9500. // Check for the "DDS" magic number
  9501. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9502. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9503. return true;
  9504. }
  9505. else {
  9506. return false;
  9507. }
  9508. }
  9509. }
  9510. catch (e) {
  9511. // Global protection
  9512. }
  9513. return false;
  9514. };
  9515. /**
  9516. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9517. * Be aware Math.random() could cause collisions, but:
  9518. * "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"
  9519. */
  9520. Tools.RandomId = function () {
  9521. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9522. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9523. return v.toString(16);
  9524. });
  9525. };
  9526. /**
  9527. * Test if the given uri is a base64 string.
  9528. * @param uri The uri to test
  9529. * @return True if the uri is a base64 string or false otherwise.
  9530. */
  9531. Tools.IsBase64 = function (uri) {
  9532. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9533. };
  9534. /**
  9535. * Decode the given base64 uri.
  9536. * @param uri The uri to decode
  9537. * @return The decoded base64 data.
  9538. */
  9539. Tools.DecodeBase64 = function (uri) {
  9540. var decodedString = atob(uri.split(",")[1]);
  9541. var bufferLength = decodedString.length;
  9542. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9543. for (var i = 0; i < bufferLength; i++) {
  9544. bufferView[i] = decodedString.charCodeAt(i);
  9545. }
  9546. return bufferView.buffer;
  9547. };
  9548. Object.defineProperty(Tools, "NoneLogLevel", {
  9549. get: function () {
  9550. return Tools._NoneLogLevel;
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Object.defineProperty(Tools, "MessageLogLevel", {
  9556. get: function () {
  9557. return Tools._MessageLogLevel;
  9558. },
  9559. enumerable: true,
  9560. configurable: true
  9561. });
  9562. Object.defineProperty(Tools, "WarningLogLevel", {
  9563. get: function () {
  9564. return Tools._WarningLogLevel;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Object.defineProperty(Tools, "ErrorLogLevel", {
  9570. get: function () {
  9571. return Tools._ErrorLogLevel;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Tools, "AllLogLevel", {
  9577. get: function () {
  9578. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Tools._AddLogEntry = function (entry) {
  9584. Tools._LogCache = entry + Tools._LogCache;
  9585. if (Tools.OnNewCacheEntry) {
  9586. Tools.OnNewCacheEntry(entry);
  9587. }
  9588. };
  9589. Tools._FormatMessage = function (message) {
  9590. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9591. var date = new Date();
  9592. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9593. };
  9594. Tools._LogDisabled = function (message) {
  9595. // nothing to do
  9596. };
  9597. Tools._LogEnabled = function (message) {
  9598. var formattedMessage = Tools._FormatMessage(message);
  9599. console.log("BJS - " + formattedMessage);
  9600. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9601. Tools._AddLogEntry(entry);
  9602. };
  9603. Tools._WarnDisabled = function (message) {
  9604. // nothing to do
  9605. };
  9606. Tools._WarnEnabled = function (message) {
  9607. var formattedMessage = Tools._FormatMessage(message);
  9608. console.warn("BJS - " + formattedMessage);
  9609. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9610. Tools._AddLogEntry(entry);
  9611. };
  9612. Tools._ErrorDisabled = function (message) {
  9613. // nothing to do
  9614. };
  9615. Tools._ErrorEnabled = function (message) {
  9616. Tools.errorsCount++;
  9617. var formattedMessage = Tools._FormatMessage(message);
  9618. console.error("BJS - " + formattedMessage);
  9619. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9620. Tools._AddLogEntry(entry);
  9621. };
  9622. Object.defineProperty(Tools, "LogCache", {
  9623. get: function () {
  9624. return Tools._LogCache;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Tools.ClearLogCache = function () {
  9630. Tools._LogCache = "";
  9631. Tools.errorsCount = 0;
  9632. };
  9633. Object.defineProperty(Tools, "LogLevels", {
  9634. set: function (level) {
  9635. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9636. Tools.Log = Tools._LogEnabled;
  9637. }
  9638. else {
  9639. Tools.Log = Tools._LogDisabled;
  9640. }
  9641. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9642. Tools.Warn = Tools._WarnEnabled;
  9643. }
  9644. else {
  9645. Tools.Warn = Tools._WarnDisabled;
  9646. }
  9647. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9648. Tools.Error = Tools._ErrorEnabled;
  9649. }
  9650. else {
  9651. Tools.Error = Tools._ErrorDisabled;
  9652. }
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Tools.IsWindowObjectExist = function () {
  9658. return (typeof window) !== "undefined";
  9659. };
  9660. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9661. get: function () {
  9662. return Tools._PerformanceNoneLogLevel;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9668. get: function () {
  9669. return Tools._PerformanceUserMarkLogLevel;
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9675. get: function () {
  9676. return Tools._PerformanceConsoleLogLevel;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9682. set: function (level) {
  9683. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9684. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9685. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9686. return;
  9687. }
  9688. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9689. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9690. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9691. return;
  9692. }
  9693. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9694. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9700. };
  9701. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9702. };
  9703. Tools._StartUserMark = function (counterName, condition) {
  9704. if (condition === void 0) { condition = true; }
  9705. if (!Tools._performance) {
  9706. if (!Tools.IsWindowObjectExist()) {
  9707. return;
  9708. }
  9709. Tools._performance = window.performance;
  9710. }
  9711. if (!condition || !Tools._performance.mark) {
  9712. return;
  9713. }
  9714. Tools._performance.mark(counterName + "-Begin");
  9715. };
  9716. Tools._EndUserMark = function (counterName, condition) {
  9717. if (condition === void 0) { condition = true; }
  9718. if (!condition || !Tools._performance.mark) {
  9719. return;
  9720. }
  9721. Tools._performance.mark(counterName + "-End");
  9722. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9723. };
  9724. Tools._StartPerformanceConsole = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!condition) {
  9727. return;
  9728. }
  9729. Tools._StartUserMark(counterName, condition);
  9730. if (console.time) {
  9731. console.time(counterName);
  9732. }
  9733. };
  9734. Tools._EndPerformanceConsole = function (counterName, condition) {
  9735. if (condition === void 0) { condition = true; }
  9736. if (!condition) {
  9737. return;
  9738. }
  9739. Tools._EndUserMark(counterName, condition);
  9740. if (console.time) {
  9741. console.timeEnd(counterName);
  9742. }
  9743. };
  9744. Object.defineProperty(Tools, "Now", {
  9745. get: function () {
  9746. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9747. return window.performance.now();
  9748. }
  9749. return Date.now();
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. /**
  9755. * This method will return the name of the class used to create the instance of the given object.
  9756. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9757. * @param object the object to get the class name from
  9758. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9759. */
  9760. Tools.GetClassName = function (object, isType) {
  9761. if (isType === void 0) { isType = false; }
  9762. var name = null;
  9763. if (!isType && object.getClassName) {
  9764. name = object.getClassName();
  9765. }
  9766. else {
  9767. if (object instanceof Object) {
  9768. var classObj = isType ? object : Object.getPrototypeOf(object);
  9769. name = classObj.constructor["__bjsclassName__"];
  9770. }
  9771. if (!name) {
  9772. name = typeof object;
  9773. }
  9774. }
  9775. return name;
  9776. };
  9777. Tools.First = function (array, predicate) {
  9778. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9779. var el = array_1[_i];
  9780. if (predicate(el)) {
  9781. return el;
  9782. }
  9783. }
  9784. return null;
  9785. };
  9786. /**
  9787. * This method will return the name of the full name of the class, including its owning module (if any).
  9788. * 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).
  9789. * @param object the object to get the class name from
  9790. * @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.
  9791. */
  9792. Tools.getFullClassName = function (object, isType) {
  9793. if (isType === void 0) { isType = false; }
  9794. var className = null;
  9795. var moduleName = null;
  9796. if (!isType && object.getClassName) {
  9797. className = object.getClassName();
  9798. }
  9799. else {
  9800. if (object instanceof Object) {
  9801. var classObj = isType ? object : Object.getPrototypeOf(object);
  9802. className = classObj.constructor["__bjsclassName__"];
  9803. moduleName = classObj.constructor["__bjsmoduleName__"];
  9804. }
  9805. if (!className) {
  9806. className = typeof object;
  9807. }
  9808. }
  9809. if (!className) {
  9810. return null;
  9811. }
  9812. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9813. };
  9814. /**
  9815. * 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.
  9816. * @param array
  9817. */
  9818. Tools.arrayOrStringFeeder = function (array) {
  9819. return function (index) {
  9820. if (index >= array.length) {
  9821. return null;
  9822. }
  9823. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9824. if (val && val.getHashCode) {
  9825. val = val.getHashCode();
  9826. }
  9827. if (typeof val === "string") {
  9828. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9829. }
  9830. return val;
  9831. };
  9832. };
  9833. /**
  9834. * Compute the hashCode of a stream of number
  9835. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9836. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9837. * @return the hash code computed
  9838. */
  9839. Tools.hashCodeFromStream = function (feeder) {
  9840. // Based from here: http://stackoverflow.com/a/7616484/802124
  9841. var hash = 0;
  9842. var index = 0;
  9843. var chr = feeder(index++);
  9844. while (chr != null) {
  9845. hash = ((hash << 5) - hash) + chr;
  9846. hash |= 0; // Convert to 32bit integer
  9847. chr = feeder(index++);
  9848. }
  9849. return hash;
  9850. };
  9851. /**
  9852. * Returns a promise that resolves after the given amount of time.
  9853. * @param delay Number of milliseconds to delay
  9854. * @returns Promise that resolves after the given amount of time
  9855. */
  9856. Tools.DelayAsync = function (delay) {
  9857. return new Promise(function (resolve) {
  9858. setTimeout(function () {
  9859. resolve();
  9860. }, delay);
  9861. });
  9862. };
  9863. Tools.BaseUrl = "";
  9864. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9865. /**
  9866. * Default behaviour for cors in the application.
  9867. * It can be a string if the expected behavior is identical in the entire app.
  9868. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9869. */
  9870. Tools.CorsBehavior = "anonymous";
  9871. Tools.UseFallbackTexture = true;
  9872. /**
  9873. * Use this object to register external classes like custom textures or material
  9874. * to allow the laoders to instantiate them
  9875. */
  9876. Tools.RegisteredExternalClasses = {};
  9877. // Used in case of a texture loading problem
  9878. 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";
  9879. Tools._tmpFloatArray = new Float32Array(1);
  9880. Tools.PreprocessUrl = function (url) {
  9881. return url;
  9882. };
  9883. // Logs
  9884. Tools._NoneLogLevel = 0;
  9885. Tools._MessageLogLevel = 1;
  9886. Tools._WarningLogLevel = 2;
  9887. Tools._ErrorLogLevel = 4;
  9888. Tools._LogCache = "";
  9889. Tools.errorsCount = 0;
  9890. Tools.Log = Tools._LogEnabled;
  9891. Tools.Warn = Tools._WarnEnabled;
  9892. Tools.Error = Tools._ErrorEnabled;
  9893. // Performances
  9894. Tools._PerformanceNoneLogLevel = 0;
  9895. Tools._PerformanceUserMarkLogLevel = 1;
  9896. Tools._PerformanceConsoleLogLevel = 2;
  9897. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9898. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9899. return Tools;
  9900. }());
  9901. BABYLON.Tools = Tools;
  9902. /**
  9903. * This class is used to track a performance counter which is number based.
  9904. * The user has access to many properties which give statistics of different nature
  9905. *
  9906. * The implementer can track two kinds of Performance Counter: time and count
  9907. * 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.
  9908. * 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.
  9909. */
  9910. var PerfCounter = /** @class */ (function () {
  9911. function PerfCounter() {
  9912. this._startMonitoringTime = 0;
  9913. this._min = 0;
  9914. this._max = 0;
  9915. this._average = 0;
  9916. this._lastSecAverage = 0;
  9917. this._current = 0;
  9918. this._totalValueCount = 0;
  9919. this._totalAccumulated = 0;
  9920. this._lastSecAccumulated = 0;
  9921. this._lastSecTime = 0;
  9922. this._lastSecValueCount = 0;
  9923. }
  9924. Object.defineProperty(PerfCounter.prototype, "min", {
  9925. /**
  9926. * Returns the smallest value ever
  9927. */
  9928. get: function () {
  9929. return this._min;
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(PerfCounter.prototype, "max", {
  9935. /**
  9936. * Returns the biggest value ever
  9937. */
  9938. get: function () {
  9939. return this._max;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(PerfCounter.prototype, "average", {
  9945. /**
  9946. * Returns the average value since the performance counter is running
  9947. */
  9948. get: function () {
  9949. return this._average;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9955. /**
  9956. * Returns the average value of the last second the counter was monitored
  9957. */
  9958. get: function () {
  9959. return this._lastSecAverage;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(PerfCounter.prototype, "current", {
  9965. /**
  9966. * Returns the current value
  9967. */
  9968. get: function () {
  9969. return this._current;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(PerfCounter.prototype, "total", {
  9975. get: function () {
  9976. return this._totalAccumulated;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(PerfCounter.prototype, "count", {
  9982. get: function () {
  9983. return this._totalValueCount;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. /**
  9989. * Call this method to start monitoring a new frame.
  9990. * 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.
  9991. */
  9992. PerfCounter.prototype.fetchNewFrame = function () {
  9993. this._totalValueCount++;
  9994. this._current = 0;
  9995. this._lastSecValueCount++;
  9996. };
  9997. /**
  9998. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9999. * @param newCount the count value to add to the monitored count
  10000. * @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.
  10001. */
  10002. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10003. if (!PerfCounter.Enabled) {
  10004. return;
  10005. }
  10006. this._current += newCount;
  10007. if (fetchResult) {
  10008. this._fetchResult();
  10009. }
  10010. };
  10011. /**
  10012. * Start monitoring this performance counter
  10013. */
  10014. PerfCounter.prototype.beginMonitoring = function () {
  10015. if (!PerfCounter.Enabled) {
  10016. return;
  10017. }
  10018. this._startMonitoringTime = Tools.Now;
  10019. };
  10020. /**
  10021. * Compute the time lapsed since the previous beginMonitoring() call.
  10022. * @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
  10023. */
  10024. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10025. if (newFrame === void 0) { newFrame = true; }
  10026. if (!PerfCounter.Enabled) {
  10027. return;
  10028. }
  10029. if (newFrame) {
  10030. this.fetchNewFrame();
  10031. }
  10032. var currentTime = Tools.Now;
  10033. this._current = currentTime - this._startMonitoringTime;
  10034. if (newFrame) {
  10035. this._fetchResult();
  10036. }
  10037. };
  10038. PerfCounter.prototype._fetchResult = function () {
  10039. this._totalAccumulated += this._current;
  10040. this._lastSecAccumulated += this._current;
  10041. // Min/Max update
  10042. this._min = Math.min(this._min, this._current);
  10043. this._max = Math.max(this._max, this._current);
  10044. this._average = this._totalAccumulated / this._totalValueCount;
  10045. // Reset last sec?
  10046. var now = Tools.Now;
  10047. if ((now - this._lastSecTime) > 1000) {
  10048. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10049. this._lastSecTime = now;
  10050. this._lastSecAccumulated = 0;
  10051. this._lastSecValueCount = 0;
  10052. }
  10053. };
  10054. PerfCounter.Enabled = true;
  10055. return PerfCounter;
  10056. }());
  10057. BABYLON.PerfCounter = PerfCounter;
  10058. /**
  10059. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10060. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10061. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10062. * @param name The name of the class, case should be preserved
  10063. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10064. */
  10065. function className(name, module) {
  10066. return function (target) {
  10067. target["__bjsclassName__"] = name;
  10068. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10069. };
  10070. }
  10071. BABYLON.className = className;
  10072. /**
  10073. * An implementation of a loop for asynchronous functions.
  10074. */
  10075. var AsyncLoop = /** @class */ (function () {
  10076. /**
  10077. * Constroctor.
  10078. * @param iterations the number of iterations.
  10079. * @param _fn the function to run each iteration
  10080. * @param _successCallback the callback that will be called upon succesful execution
  10081. * @param offset starting offset.
  10082. */
  10083. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10084. if (offset === void 0) { offset = 0; }
  10085. this.iterations = iterations;
  10086. this._fn = _fn;
  10087. this._successCallback = _successCallback;
  10088. this.index = offset - 1;
  10089. this._done = false;
  10090. }
  10091. /**
  10092. * Execute the next iteration. Must be called after the last iteration was finished.
  10093. */
  10094. AsyncLoop.prototype.executeNext = function () {
  10095. if (!this._done) {
  10096. if (this.index + 1 < this.iterations) {
  10097. ++this.index;
  10098. this._fn(this);
  10099. }
  10100. else {
  10101. this.breakLoop();
  10102. }
  10103. }
  10104. };
  10105. /**
  10106. * Break the loop and run the success callback.
  10107. */
  10108. AsyncLoop.prototype.breakLoop = function () {
  10109. this._done = true;
  10110. this._successCallback();
  10111. };
  10112. /**
  10113. * Helper function
  10114. */
  10115. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10116. if (offset === void 0) { offset = 0; }
  10117. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10118. loop.executeNext();
  10119. return loop;
  10120. };
  10121. /**
  10122. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10123. * @param iterations total number of iterations
  10124. * @param syncedIterations number of synchronous iterations in each async iteration.
  10125. * @param fn the function to call each iteration.
  10126. * @param callback a success call back that will be called when iterating stops.
  10127. * @param breakFunction a break condition (optional)
  10128. * @param timeout timeout settings for the setTimeout function. default - 0.
  10129. * @constructor
  10130. */
  10131. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10132. if (timeout === void 0) { timeout = 0; }
  10133. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10134. if (breakFunction && breakFunction())
  10135. loop.breakLoop();
  10136. else {
  10137. setTimeout(function () {
  10138. for (var i = 0; i < syncedIterations; ++i) {
  10139. var iteration = (loop.index * syncedIterations) + i;
  10140. if (iteration >= iterations)
  10141. break;
  10142. fn(iteration);
  10143. if (breakFunction && breakFunction()) {
  10144. loop.breakLoop();
  10145. break;
  10146. }
  10147. }
  10148. loop.executeNext();
  10149. }, timeout);
  10150. }
  10151. }, callback);
  10152. };
  10153. return AsyncLoop;
  10154. }());
  10155. BABYLON.AsyncLoop = AsyncLoop;
  10156. })(BABYLON || (BABYLON = {}));
  10157. //# sourceMappingURL=babylon.tools.js.map
  10158. var BABYLON;
  10159. (function (BABYLON) {
  10160. var PromiseStates;
  10161. (function (PromiseStates) {
  10162. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10163. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10164. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10165. })(PromiseStates || (PromiseStates = {}));
  10166. var FulFillmentAgregator = /** @class */ (function () {
  10167. function FulFillmentAgregator() {
  10168. this.count = 0;
  10169. this.target = 0;
  10170. this.results = [];
  10171. }
  10172. return FulFillmentAgregator;
  10173. }());
  10174. var InternalPromise = /** @class */ (function () {
  10175. function InternalPromise(resolver) {
  10176. var _this = this;
  10177. this._state = PromiseStates.Pending;
  10178. this._children = new Array();
  10179. this._rejectWasConsumed = false;
  10180. if (!resolver) {
  10181. return;
  10182. }
  10183. try {
  10184. resolver(function (value) {
  10185. _this._resolve(value);
  10186. }, function (reason) {
  10187. _this._reject(reason);
  10188. });
  10189. }
  10190. catch (e) {
  10191. this._reject(e);
  10192. }
  10193. }
  10194. Object.defineProperty(InternalPromise.prototype, "_result", {
  10195. get: function () {
  10196. return this._resultValue;
  10197. },
  10198. set: function (value) {
  10199. this._resultValue = value;
  10200. if (this._parent && this._parent._result === undefined) {
  10201. this._parent._result = value;
  10202. }
  10203. },
  10204. enumerable: true,
  10205. configurable: true
  10206. });
  10207. InternalPromise.prototype.catch = function (onRejected) {
  10208. return this.then(undefined, onRejected);
  10209. };
  10210. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10211. var _this = this;
  10212. var newPromise = new InternalPromise();
  10213. newPromise._onFulfilled = onFulfilled;
  10214. newPromise._onRejected = onRejected;
  10215. // Composition
  10216. this._children.push(newPromise);
  10217. newPromise._parent = this;
  10218. if (this._state !== PromiseStates.Pending) {
  10219. BABYLON.Tools.SetImmediate(function () {
  10220. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10221. var returnedValue = newPromise._resolve(_this._result);
  10222. if (returnedValue !== undefined && returnedValue !== null) {
  10223. if (returnedValue._state !== undefined) {
  10224. var returnedPromise = returnedValue;
  10225. newPromise._children.push(returnedPromise);
  10226. returnedPromise._parent = newPromise;
  10227. newPromise = returnedPromise;
  10228. }
  10229. else {
  10230. newPromise._result = returnedValue;
  10231. }
  10232. }
  10233. }
  10234. else {
  10235. newPromise._reject(_this._reason);
  10236. }
  10237. });
  10238. }
  10239. return newPromise;
  10240. };
  10241. InternalPromise.prototype._moveChildren = function (children) {
  10242. var _this = this;
  10243. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10244. this._children.forEach(function (child) {
  10245. child._parent = _this;
  10246. });
  10247. if (this._state === PromiseStates.Fulfilled) {
  10248. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10249. var child = _b[_i];
  10250. child._resolve(this._result);
  10251. }
  10252. }
  10253. else if (this._state === PromiseStates.Rejected) {
  10254. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10255. var child = _d[_c];
  10256. child._reject(this._reason);
  10257. }
  10258. }
  10259. var _a;
  10260. };
  10261. InternalPromise.prototype._resolve = function (value) {
  10262. try {
  10263. this._state = PromiseStates.Fulfilled;
  10264. var returnedValue = null;
  10265. if (this._onFulfilled) {
  10266. returnedValue = this._onFulfilled(value);
  10267. }
  10268. if (returnedValue !== undefined && returnedValue !== null) {
  10269. if (returnedValue._state !== undefined) {
  10270. // Transmit children
  10271. var returnedPromise = returnedValue;
  10272. returnedPromise._parent = this;
  10273. returnedPromise._moveChildren(this._children);
  10274. value = returnedPromise._result;
  10275. }
  10276. else {
  10277. value = returnedValue;
  10278. }
  10279. }
  10280. this._result = value;
  10281. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10282. var child = _a[_i];
  10283. child._resolve(value);
  10284. }
  10285. this._children.length = 0;
  10286. delete this._onFulfilled;
  10287. delete this._onRejected;
  10288. }
  10289. catch (e) {
  10290. this._reject(e, true);
  10291. }
  10292. };
  10293. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10294. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10295. this._state = PromiseStates.Rejected;
  10296. this._reason = reason;
  10297. if (this._onRejected && !onLocalThrow) {
  10298. try {
  10299. this._onRejected(reason);
  10300. this._rejectWasConsumed = true;
  10301. }
  10302. catch (e) {
  10303. reason = e;
  10304. }
  10305. }
  10306. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10307. var child = _a[_i];
  10308. if (this._rejectWasConsumed) {
  10309. child._resolve(null);
  10310. }
  10311. else {
  10312. child._reject(reason);
  10313. }
  10314. }
  10315. this._children.length = 0;
  10316. delete this._onFulfilled;
  10317. delete this._onRejected;
  10318. };
  10319. InternalPromise.resolve = function (value) {
  10320. var newPromise = new InternalPromise();
  10321. newPromise._resolve(value);
  10322. return newPromise;
  10323. };
  10324. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10325. promise.then(function (value) {
  10326. agregator.results[index] = value;
  10327. agregator.count++;
  10328. if (agregator.count === agregator.target) {
  10329. agregator.rootPromise._resolve(agregator.results);
  10330. }
  10331. return null;
  10332. }, function (reason) {
  10333. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10334. agregator.rootPromise._reject(reason);
  10335. }
  10336. });
  10337. };
  10338. InternalPromise.all = function (promises) {
  10339. var newPromise = new InternalPromise();
  10340. var agregator = new FulFillmentAgregator();
  10341. agregator.target = promises.length;
  10342. agregator.rootPromise = newPromise;
  10343. if (promises.length) {
  10344. for (var index = 0; index < promises.length; index++) {
  10345. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10346. }
  10347. }
  10348. else {
  10349. newPromise._resolve([]);
  10350. }
  10351. return newPromise;
  10352. };
  10353. InternalPromise.race = function (promises) {
  10354. var newPromise = new InternalPromise();
  10355. if (promises.length) {
  10356. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10357. var promise = promises_1[_i];
  10358. promise.then(function (value) {
  10359. if (newPromise) {
  10360. newPromise._resolve(value);
  10361. newPromise = null;
  10362. }
  10363. return null;
  10364. }, function (reason) {
  10365. if (newPromise) {
  10366. newPromise._reject(reason);
  10367. newPromise = null;
  10368. }
  10369. });
  10370. }
  10371. }
  10372. return newPromise;
  10373. };
  10374. return InternalPromise;
  10375. }());
  10376. /**
  10377. * Helper class that provides a small promise polyfill
  10378. */
  10379. var PromisePolyfill = /** @class */ (function () {
  10380. function PromisePolyfill() {
  10381. }
  10382. /**
  10383. * Static function used to check if the polyfill is required
  10384. * If this is the case then the function will inject the polyfill to window.Promise
  10385. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10386. */
  10387. PromisePolyfill.Apply = function (force) {
  10388. if (force === void 0) { force = false; }
  10389. if (force || typeof Promise === 'undefined') {
  10390. var root = window;
  10391. root.Promise = InternalPromise;
  10392. }
  10393. };
  10394. return PromisePolyfill;
  10395. }());
  10396. BABYLON.PromisePolyfill = PromisePolyfill;
  10397. })(BABYLON || (BABYLON = {}));
  10398. //# sourceMappingURL=babylon.promise.js.map
  10399. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10400. var BABYLON;
  10401. (function (BABYLON) {
  10402. /**
  10403. * Helper class to push actions to a pool of workers.
  10404. */
  10405. var WorkerPool = /** @class */ (function () {
  10406. /**
  10407. * Constructor
  10408. * @param workers Array of workers to use for actions
  10409. */
  10410. function WorkerPool(workers) {
  10411. this._pendingActions = new Array();
  10412. this._workerInfos = workers.map(function (worker) { return ({
  10413. worker: worker,
  10414. active: false
  10415. }); });
  10416. }
  10417. /**
  10418. * Terminates all workers and clears any pending actions.
  10419. */
  10420. WorkerPool.prototype.dispose = function () {
  10421. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10422. var workerInfo = _a[_i];
  10423. workerInfo.worker.terminate();
  10424. }
  10425. delete this._workerInfos;
  10426. delete this._pendingActions;
  10427. };
  10428. /**
  10429. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10430. * pended until a worker has completed its action.
  10431. * @param action The action to perform. Call onComplete when the action is complete.
  10432. */
  10433. WorkerPool.prototype.push = function (action) {
  10434. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10435. var workerInfo = _a[_i];
  10436. if (!workerInfo.active) {
  10437. this._execute(workerInfo, action);
  10438. return;
  10439. }
  10440. }
  10441. this._pendingActions.push(action);
  10442. };
  10443. WorkerPool.prototype._execute = function (workerInfo, action) {
  10444. var _this = this;
  10445. workerInfo.active = true;
  10446. action(workerInfo.worker, function () {
  10447. workerInfo.active = false;
  10448. var nextAction = _this._pendingActions.shift();
  10449. if (nextAction) {
  10450. _this._execute(workerInfo, nextAction);
  10451. }
  10452. });
  10453. };
  10454. return WorkerPool;
  10455. }());
  10456. BABYLON.WorkerPool = WorkerPool;
  10457. })(BABYLON || (BABYLON = {}));
  10458. //# sourceMappingURL=babylon.workerPool.js.map
  10459. var BABYLON;
  10460. (function (BABYLON) {
  10461. /**
  10462. * @hidden
  10463. **/
  10464. var _AlphaState = /** @class */ (function () {
  10465. /**
  10466. * Initializes the state.
  10467. */
  10468. function _AlphaState() {
  10469. this._isAlphaBlendDirty = false;
  10470. this._isBlendFunctionParametersDirty = false;
  10471. this._isBlendEquationParametersDirty = false;
  10472. this._isBlendConstantsDirty = false;
  10473. this._alphaBlend = false;
  10474. this._blendFunctionParameters = new Array(4);
  10475. this._blendEquationParameters = new Array(2);
  10476. this._blendConstants = new Array(4);
  10477. this.reset();
  10478. }
  10479. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10480. get: function () {
  10481. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10482. },
  10483. enumerable: true,
  10484. configurable: true
  10485. });
  10486. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10487. get: function () {
  10488. return this._alphaBlend;
  10489. },
  10490. set: function (value) {
  10491. if (this._alphaBlend === value) {
  10492. return;
  10493. }
  10494. this._alphaBlend = value;
  10495. this._isAlphaBlendDirty = true;
  10496. },
  10497. enumerable: true,
  10498. configurable: true
  10499. });
  10500. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10501. if (this._blendConstants[0] === r &&
  10502. this._blendConstants[1] === g &&
  10503. this._blendConstants[2] === b &&
  10504. this._blendConstants[3] === a) {
  10505. return;
  10506. }
  10507. this._blendConstants[0] = r;
  10508. this._blendConstants[1] = g;
  10509. this._blendConstants[2] = b;
  10510. this._blendConstants[3] = a;
  10511. this._isBlendConstantsDirty = true;
  10512. };
  10513. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10514. if (this._blendFunctionParameters[0] === value0 &&
  10515. this._blendFunctionParameters[1] === value1 &&
  10516. this._blendFunctionParameters[2] === value2 &&
  10517. this._blendFunctionParameters[3] === value3) {
  10518. return;
  10519. }
  10520. this._blendFunctionParameters[0] = value0;
  10521. this._blendFunctionParameters[1] = value1;
  10522. this._blendFunctionParameters[2] = value2;
  10523. this._blendFunctionParameters[3] = value3;
  10524. this._isBlendFunctionParametersDirty = true;
  10525. };
  10526. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10527. if (this._blendEquationParameters[0] === rgb &&
  10528. this._blendEquationParameters[1] === alpha) {
  10529. return;
  10530. }
  10531. this._blendEquationParameters[0] = rgb;
  10532. this._blendEquationParameters[1] = alpha;
  10533. this._isBlendEquationParametersDirty = true;
  10534. };
  10535. _AlphaState.prototype.reset = function () {
  10536. this._alphaBlend = false;
  10537. this._blendFunctionParameters[0] = null;
  10538. this._blendFunctionParameters[1] = null;
  10539. this._blendFunctionParameters[2] = null;
  10540. this._blendFunctionParameters[3] = null;
  10541. this._blendEquationParameters[0] = null;
  10542. this._blendEquationParameters[1] = null;
  10543. this._blendConstants[0] = null;
  10544. this._blendConstants[1] = null;
  10545. this._blendConstants[2] = null;
  10546. this._blendConstants[3] = null;
  10547. this._isAlphaBlendDirty = true;
  10548. this._isBlendFunctionParametersDirty = false;
  10549. this._isBlendEquationParametersDirty = false;
  10550. this._isBlendConstantsDirty = false;
  10551. };
  10552. _AlphaState.prototype.apply = function (gl) {
  10553. if (!this.isDirty) {
  10554. return;
  10555. }
  10556. // Alpha blend
  10557. if (this._isAlphaBlendDirty) {
  10558. if (this._alphaBlend) {
  10559. gl.enable(gl.BLEND);
  10560. }
  10561. else {
  10562. gl.disable(gl.BLEND);
  10563. }
  10564. this._isAlphaBlendDirty = false;
  10565. }
  10566. // Alpha function
  10567. if (this._isBlendFunctionParametersDirty) {
  10568. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10569. this._isBlendFunctionParametersDirty = false;
  10570. }
  10571. // Alpha equation
  10572. if (this._isBlendEquationParametersDirty) {
  10573. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10574. this._isBlendEquationParametersDirty = false;
  10575. }
  10576. // Constants
  10577. if (this._isBlendConstantsDirty) {
  10578. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10579. this._isBlendConstantsDirty = false;
  10580. }
  10581. };
  10582. return _AlphaState;
  10583. }());
  10584. BABYLON._AlphaState = _AlphaState;
  10585. })(BABYLON || (BABYLON = {}));
  10586. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10587. var BABYLON;
  10588. (function (BABYLON) {
  10589. /**
  10590. * @hidden
  10591. **/
  10592. var _DepthCullingState = /** @class */ (function () {
  10593. /**
  10594. * Initializes the state.
  10595. */
  10596. function _DepthCullingState() {
  10597. this._isDepthTestDirty = false;
  10598. this._isDepthMaskDirty = false;
  10599. this._isDepthFuncDirty = false;
  10600. this._isCullFaceDirty = false;
  10601. this._isCullDirty = false;
  10602. this._isZOffsetDirty = false;
  10603. this._isFrontFaceDirty = false;
  10604. this.reset();
  10605. }
  10606. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10607. get: function () {
  10608. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10614. get: function () {
  10615. return this._zOffset;
  10616. },
  10617. set: function (value) {
  10618. if (this._zOffset === value) {
  10619. return;
  10620. }
  10621. this._zOffset = value;
  10622. this._isZOffsetDirty = true;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10628. get: function () {
  10629. return this._cullFace;
  10630. },
  10631. set: function (value) {
  10632. if (this._cullFace === value) {
  10633. return;
  10634. }
  10635. this._cullFace = value;
  10636. this._isCullFaceDirty = true;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10642. get: function () {
  10643. return this._cull;
  10644. },
  10645. set: function (value) {
  10646. if (this._cull === value) {
  10647. return;
  10648. }
  10649. this._cull = value;
  10650. this._isCullDirty = true;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10656. get: function () {
  10657. return this._depthFunc;
  10658. },
  10659. set: function (value) {
  10660. if (this._depthFunc === value) {
  10661. return;
  10662. }
  10663. this._depthFunc = value;
  10664. this._isDepthFuncDirty = true;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10670. get: function () {
  10671. return this._depthMask;
  10672. },
  10673. set: function (value) {
  10674. if (this._depthMask === value) {
  10675. return;
  10676. }
  10677. this._depthMask = value;
  10678. this._isDepthMaskDirty = true;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10684. get: function () {
  10685. return this._depthTest;
  10686. },
  10687. set: function (value) {
  10688. if (this._depthTest === value) {
  10689. return;
  10690. }
  10691. this._depthTest = value;
  10692. this._isDepthTestDirty = true;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10698. get: function () {
  10699. return this._frontFace;
  10700. },
  10701. set: function (value) {
  10702. if (this._frontFace === value) {
  10703. return;
  10704. }
  10705. this._frontFace = value;
  10706. this._isFrontFaceDirty = true;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. _DepthCullingState.prototype.reset = function () {
  10712. this._depthMask = true;
  10713. this._depthTest = true;
  10714. this._depthFunc = null;
  10715. this._cullFace = null;
  10716. this._cull = null;
  10717. this._zOffset = 0;
  10718. this._frontFace = null;
  10719. this._isDepthTestDirty = true;
  10720. this._isDepthMaskDirty = true;
  10721. this._isDepthFuncDirty = false;
  10722. this._isCullFaceDirty = false;
  10723. this._isCullDirty = false;
  10724. this._isZOffsetDirty = false;
  10725. this._isFrontFaceDirty = false;
  10726. };
  10727. _DepthCullingState.prototype.apply = function (gl) {
  10728. if (!this.isDirty) {
  10729. return;
  10730. }
  10731. // Cull
  10732. if (this._isCullDirty) {
  10733. if (this.cull) {
  10734. gl.enable(gl.CULL_FACE);
  10735. }
  10736. else {
  10737. gl.disable(gl.CULL_FACE);
  10738. }
  10739. this._isCullDirty = false;
  10740. }
  10741. // Cull face
  10742. if (this._isCullFaceDirty) {
  10743. gl.cullFace(this.cullFace);
  10744. this._isCullFaceDirty = false;
  10745. }
  10746. // Depth mask
  10747. if (this._isDepthMaskDirty) {
  10748. gl.depthMask(this.depthMask);
  10749. this._isDepthMaskDirty = false;
  10750. }
  10751. // Depth test
  10752. if (this._isDepthTestDirty) {
  10753. if (this.depthTest) {
  10754. gl.enable(gl.DEPTH_TEST);
  10755. }
  10756. else {
  10757. gl.disable(gl.DEPTH_TEST);
  10758. }
  10759. this._isDepthTestDirty = false;
  10760. }
  10761. // Depth func
  10762. if (this._isDepthFuncDirty) {
  10763. gl.depthFunc(this.depthFunc);
  10764. this._isDepthFuncDirty = false;
  10765. }
  10766. // zOffset
  10767. if (this._isZOffsetDirty) {
  10768. if (this.zOffset) {
  10769. gl.enable(gl.POLYGON_OFFSET_FILL);
  10770. gl.polygonOffset(this.zOffset, 0);
  10771. }
  10772. else {
  10773. gl.disable(gl.POLYGON_OFFSET_FILL);
  10774. }
  10775. this._isZOffsetDirty = false;
  10776. }
  10777. // Front face
  10778. if (this._isFrontFaceDirty) {
  10779. gl.frontFace(this.frontFace);
  10780. this._isFrontFaceDirty = false;
  10781. }
  10782. };
  10783. return _DepthCullingState;
  10784. }());
  10785. BABYLON._DepthCullingState = _DepthCullingState;
  10786. })(BABYLON || (BABYLON = {}));
  10787. //# sourceMappingURL=babylon.depthCullingState.js.map
  10788. var BABYLON;
  10789. (function (BABYLON) {
  10790. /**
  10791. * @hidden
  10792. **/
  10793. var _StencilState = /** @class */ (function () {
  10794. function _StencilState() {
  10795. this._isStencilTestDirty = false;
  10796. this._isStencilMaskDirty = false;
  10797. this._isStencilFuncDirty = false;
  10798. this._isStencilOpDirty = false;
  10799. this.reset();
  10800. }
  10801. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10802. get: function () {
  10803. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10809. get: function () {
  10810. return this._stencilFunc;
  10811. },
  10812. set: function (value) {
  10813. if (this._stencilFunc === value) {
  10814. return;
  10815. }
  10816. this._stencilFunc = value;
  10817. this._isStencilFuncDirty = true;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10823. get: function () {
  10824. return this._stencilFuncRef;
  10825. },
  10826. set: function (value) {
  10827. if (this._stencilFuncRef === value) {
  10828. return;
  10829. }
  10830. this._stencilFuncRef = value;
  10831. this._isStencilFuncDirty = true;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10837. get: function () {
  10838. return this._stencilFuncMask;
  10839. },
  10840. set: function (value) {
  10841. if (this._stencilFuncMask === value) {
  10842. return;
  10843. }
  10844. this._stencilFuncMask = value;
  10845. this._isStencilFuncDirty = true;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10851. get: function () {
  10852. return this._stencilOpStencilFail;
  10853. },
  10854. set: function (value) {
  10855. if (this._stencilOpStencilFail === value) {
  10856. return;
  10857. }
  10858. this._stencilOpStencilFail = value;
  10859. this._isStencilOpDirty = true;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10865. get: function () {
  10866. return this._stencilOpDepthFail;
  10867. },
  10868. set: function (value) {
  10869. if (this._stencilOpDepthFail === value) {
  10870. return;
  10871. }
  10872. this._stencilOpDepthFail = value;
  10873. this._isStencilOpDirty = true;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10879. get: function () {
  10880. return this._stencilOpStencilDepthPass;
  10881. },
  10882. set: function (value) {
  10883. if (this._stencilOpStencilDepthPass === value) {
  10884. return;
  10885. }
  10886. this._stencilOpStencilDepthPass = value;
  10887. this._isStencilOpDirty = true;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10893. get: function () {
  10894. return this._stencilMask;
  10895. },
  10896. set: function (value) {
  10897. if (this._stencilMask === value) {
  10898. return;
  10899. }
  10900. this._stencilMask = value;
  10901. this._isStencilMaskDirty = true;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10907. get: function () {
  10908. return this._stencilTest;
  10909. },
  10910. set: function (value) {
  10911. if (this._stencilTest === value) {
  10912. return;
  10913. }
  10914. this._stencilTest = value;
  10915. this._isStencilTestDirty = true;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. _StencilState.prototype.reset = function () {
  10921. this._stencilTest = false;
  10922. this._stencilMask = 0xFF;
  10923. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10924. this._stencilFuncRef = 1;
  10925. this._stencilFuncMask = 0xFF;
  10926. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10927. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10928. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10929. this._isStencilTestDirty = true;
  10930. this._isStencilMaskDirty = true;
  10931. this._isStencilFuncDirty = true;
  10932. this._isStencilOpDirty = true;
  10933. };
  10934. _StencilState.prototype.apply = function (gl) {
  10935. if (!this.isDirty) {
  10936. return;
  10937. }
  10938. // Stencil test
  10939. if (this._isStencilTestDirty) {
  10940. if (this.stencilTest) {
  10941. gl.enable(gl.STENCIL_TEST);
  10942. }
  10943. else {
  10944. gl.disable(gl.STENCIL_TEST);
  10945. }
  10946. this._isStencilTestDirty = false;
  10947. }
  10948. // Stencil mask
  10949. if (this._isStencilMaskDirty) {
  10950. gl.stencilMask(this.stencilMask);
  10951. this._isStencilMaskDirty = false;
  10952. }
  10953. // Stencil func
  10954. if (this._isStencilFuncDirty) {
  10955. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10956. this._isStencilFuncDirty = false;
  10957. }
  10958. // Stencil op
  10959. if (this._isStencilOpDirty) {
  10960. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10961. this._isStencilOpDirty = false;
  10962. }
  10963. };
  10964. return _StencilState;
  10965. }());
  10966. BABYLON._StencilState = _StencilState;
  10967. })(BABYLON || (BABYLON = {}));
  10968. //# sourceMappingURL=babylon.stencilState.js.map
  10969. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10970. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10971. s = arguments[i];
  10972. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10973. t[p] = s[p];
  10974. }
  10975. return t;
  10976. };
  10977. var BABYLON;
  10978. (function (BABYLON) {
  10979. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10980. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10981. };
  10982. var compileRawShader = function (gl, source, type) {
  10983. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10984. gl.shaderSource(shader, source);
  10985. gl.compileShader(shader);
  10986. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10987. var log = gl.getShaderInfoLog(shader);
  10988. if (log) {
  10989. throw new Error(log);
  10990. }
  10991. }
  10992. if (!shader) {
  10993. throw new Error("Something went wrong while compile the shader.");
  10994. }
  10995. return shader;
  10996. };
  10997. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10998. var magFilter = gl.NEAREST;
  10999. var minFilter = gl.NEAREST;
  11000. switch (samplingMode) {
  11001. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11002. magFilter = gl.LINEAR;
  11003. if (generateMipMaps) {
  11004. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11005. }
  11006. else {
  11007. minFilter = gl.LINEAR;
  11008. }
  11009. break;
  11010. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11011. magFilter = gl.LINEAR;
  11012. if (generateMipMaps) {
  11013. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11014. }
  11015. else {
  11016. minFilter = gl.LINEAR;
  11017. }
  11018. break;
  11019. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11020. magFilter = gl.NEAREST;
  11021. if (generateMipMaps) {
  11022. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11023. }
  11024. else {
  11025. minFilter = gl.NEAREST;
  11026. }
  11027. break;
  11028. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11029. magFilter = gl.NEAREST;
  11030. if (generateMipMaps) {
  11031. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11032. }
  11033. else {
  11034. minFilter = gl.NEAREST;
  11035. }
  11036. break;
  11037. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11038. magFilter = gl.NEAREST;
  11039. if (generateMipMaps) {
  11040. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11041. }
  11042. else {
  11043. minFilter = gl.LINEAR;
  11044. }
  11045. break;
  11046. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11047. magFilter = gl.NEAREST;
  11048. if (generateMipMaps) {
  11049. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11050. }
  11051. else {
  11052. minFilter = gl.LINEAR;
  11053. }
  11054. break;
  11055. case BABYLON.Texture.NEAREST_LINEAR:
  11056. magFilter = gl.NEAREST;
  11057. minFilter = gl.LINEAR;
  11058. break;
  11059. case BABYLON.Texture.NEAREST_NEAREST:
  11060. magFilter = gl.NEAREST;
  11061. minFilter = gl.NEAREST;
  11062. break;
  11063. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11064. magFilter = gl.LINEAR;
  11065. if (generateMipMaps) {
  11066. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11067. }
  11068. else {
  11069. minFilter = gl.NEAREST;
  11070. }
  11071. break;
  11072. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11073. magFilter = gl.LINEAR;
  11074. if (generateMipMaps) {
  11075. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11076. }
  11077. else {
  11078. minFilter = gl.NEAREST;
  11079. }
  11080. break;
  11081. case BABYLON.Texture.LINEAR_LINEAR:
  11082. magFilter = gl.LINEAR;
  11083. minFilter = gl.LINEAR;
  11084. break;
  11085. case BABYLON.Texture.LINEAR_NEAREST:
  11086. magFilter = gl.LINEAR;
  11087. minFilter = gl.NEAREST;
  11088. break;
  11089. }
  11090. return {
  11091. min: minFilter,
  11092. mag: magFilter
  11093. };
  11094. };
  11095. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11096. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11097. var img;
  11098. var onload = function () {
  11099. loadedImages[index] = img;
  11100. loadedImages._internalCount++;
  11101. if (scene) {
  11102. scene._removePendingData(img);
  11103. }
  11104. if (loadedImages._internalCount === 6) {
  11105. onfinish(loadedImages);
  11106. }
  11107. };
  11108. var onerror = function (message, exception) {
  11109. if (scene) {
  11110. scene._removePendingData(img);
  11111. }
  11112. if (onErrorCallBack) {
  11113. onErrorCallBack(message, exception);
  11114. }
  11115. };
  11116. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11117. if (scene) {
  11118. scene._addPendingData(img);
  11119. }
  11120. };
  11121. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11122. if (onError === void 0) { onError = null; }
  11123. var loadedImages = [];
  11124. loadedImages._internalCount = 0;
  11125. for (var index = 0; index < 6; index++) {
  11126. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11127. }
  11128. };
  11129. var BufferPointer = /** @class */ (function () {
  11130. function BufferPointer() {
  11131. }
  11132. return BufferPointer;
  11133. }());
  11134. /**
  11135. * Interface for attribute information associated with buffer instanciation
  11136. */
  11137. var InstancingAttributeInfo = /** @class */ (function () {
  11138. function InstancingAttributeInfo() {
  11139. }
  11140. return InstancingAttributeInfo;
  11141. }());
  11142. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11143. /**
  11144. * Define options used to create a render target texture
  11145. */
  11146. var RenderTargetCreationOptions = /** @class */ (function () {
  11147. function RenderTargetCreationOptions() {
  11148. }
  11149. return RenderTargetCreationOptions;
  11150. }());
  11151. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11152. /**
  11153. * Define options used to create a depth texture
  11154. */
  11155. var DepthTextureCreationOptions = /** @class */ (function () {
  11156. function DepthTextureCreationOptions() {
  11157. }
  11158. return DepthTextureCreationOptions;
  11159. }());
  11160. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11161. /**
  11162. * Class used to describe the capabilities of the engine relatively to the current browser
  11163. */
  11164. var EngineCapabilities = /** @class */ (function () {
  11165. function EngineCapabilities() {
  11166. }
  11167. return EngineCapabilities;
  11168. }());
  11169. BABYLON.EngineCapabilities = EngineCapabilities;
  11170. /**
  11171. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11172. */
  11173. var Engine = /** @class */ (function () {
  11174. /**
  11175. * Creates a new engine
  11176. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11177. * @param antialias defines enable antialiasing (default: false)
  11178. * @param options defines further options to be sent to the getContext() function
  11179. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11180. */
  11181. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11182. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11183. var _this = this;
  11184. // Public members
  11185. /**
  11186. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11187. */
  11188. this.forcePOTTextures = false;
  11189. /**
  11190. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11191. */
  11192. this.isFullscreen = false;
  11193. /**
  11194. * Gets a boolean indicating if the pointer is currently locked
  11195. */
  11196. this.isPointerLock = false;
  11197. /**
  11198. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11199. */
  11200. this.cullBackFaces = true;
  11201. /**
  11202. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11203. */
  11204. this.renderEvenInBackground = true;
  11205. /**
  11206. * Gets or sets a boolean indicating that cache can be kept between frames
  11207. */
  11208. this.preventCacheWipeBetweenFrames = false;
  11209. /**
  11210. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11211. **/
  11212. this.enableOfflineSupport = false;
  11213. /**
  11214. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11215. **/
  11216. this.disableManifestCheck = false;
  11217. /**
  11218. * Gets the list of created scenes
  11219. */
  11220. this.scenes = new Array();
  11221. /**
  11222. * Gets the list of created postprocesses
  11223. */
  11224. this.postProcesses = new Array();
  11225. // Observables
  11226. /**
  11227. * Observable event triggered each time the rendering canvas is resized
  11228. */
  11229. this.onResizeObservable = new BABYLON.Observable();
  11230. /**
  11231. * Observable event triggered each time the canvas loses focus
  11232. */
  11233. this.onCanvasBlurObservable = new BABYLON.Observable();
  11234. /**
  11235. * Observable event triggered each time the canvas gains focus
  11236. */
  11237. this.onCanvasFocusObservable = new BABYLON.Observable();
  11238. /**
  11239. * Observable event triggered each time the canvas receives pointerout event
  11240. */
  11241. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11242. /**
  11243. * Observable event triggered before each texture is initialized
  11244. */
  11245. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11246. //WebVR
  11247. this._vrDisplay = undefined;
  11248. this._vrSupported = false;
  11249. this._vrExclusivePointerMode = false;
  11250. // Uniform buffers list
  11251. /**
  11252. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11253. */
  11254. this.disableUniformBuffers = false;
  11255. /** @hidden */
  11256. this._uniformBuffers = new Array();
  11257. // Observables
  11258. /**
  11259. * Observable raised when the engine begins a new frame
  11260. */
  11261. this.onBeginFrameObservable = new BABYLON.Observable();
  11262. /**
  11263. * Observable raised when the engine ends the current frame
  11264. */
  11265. this.onEndFrameObservable = new BABYLON.Observable();
  11266. /**
  11267. * Observable raised when the engine is about to compile a shader
  11268. */
  11269. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11270. /**
  11271. * Observable raised when the engine has jsut compiled a shader
  11272. */
  11273. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11274. this._windowIsBackground = false;
  11275. this._webGLVersion = 1.0;
  11276. /** @hidden */
  11277. this._badOS = false;
  11278. /** @hidden */
  11279. this._badDesktopOS = false;
  11280. /**
  11281. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11282. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11283. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11284. */
  11285. this.disableTextureBindingOptimization = false;
  11286. /**
  11287. * Observable signaled when VR display mode changes
  11288. */
  11289. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11290. /**
  11291. * Observable signaled when VR request present is complete
  11292. */
  11293. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11294. /**
  11295. * Observable signaled when VR request present starts
  11296. */
  11297. this.onVRRequestPresentStart = new BABYLON.Observable();
  11298. this._colorWrite = true;
  11299. /** @hidden */
  11300. this._drawCalls = new BABYLON.PerfCounter();
  11301. /** @hidden */
  11302. this._textureCollisions = new BABYLON.PerfCounter();
  11303. this._renderingQueueLaunched = false;
  11304. this._activeRenderLoops = new Array();
  11305. // Deterministic lockstepMaxSteps
  11306. this._deterministicLockstep = false;
  11307. this._lockstepMaxSteps = 4;
  11308. // Lost context
  11309. /**
  11310. * Observable signaled when a context lost event is raised
  11311. */
  11312. this.onContextLostObservable = new BABYLON.Observable();
  11313. /**
  11314. * Observable signaled when a context restored event is raised
  11315. */
  11316. this.onContextRestoredObservable = new BABYLON.Observable();
  11317. this._contextWasLost = false;
  11318. this._doNotHandleContextLost = false;
  11319. // FPS
  11320. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11321. this._fps = 60;
  11322. this._deltaTime = 0;
  11323. /**
  11324. * Turn this value on if you want to pause FPS computation when in background
  11325. */
  11326. this.disablePerformanceMonitorInBackground = false;
  11327. // States
  11328. /** @hidden */
  11329. this._depthCullingState = new BABYLON._DepthCullingState();
  11330. /** @hidden */
  11331. this._stencilState = new BABYLON._StencilState();
  11332. /** @hidden */
  11333. this._alphaState = new BABYLON._AlphaState();
  11334. /** @hidden */
  11335. this._alphaMode = Engine.ALPHA_DISABLE;
  11336. // Cache
  11337. this._internalTexturesCache = new Array();
  11338. /** @hidden */
  11339. this._activeChannel = 0;
  11340. this._currentTextureChannel = -1;
  11341. /** @hidden */
  11342. this._boundTexturesCache = {};
  11343. this._compiledEffects = {};
  11344. this._vertexAttribArraysEnabled = [];
  11345. this._uintIndicesCurrentlySet = false;
  11346. this._currentBoundBuffer = new Array();
  11347. this._currentBufferPointers = new Array();
  11348. this._currentInstanceLocations = new Array();
  11349. this._currentInstanceBuffers = new Array();
  11350. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11351. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11352. this._vaoRecordInProgress = false;
  11353. this._mustWipeVertexAttributes = false;
  11354. this._nextFreeTextureSlots = new Array();
  11355. this._maxSimultaneousTextures = 0;
  11356. this._activeRequests = new Array();
  11357. // Hardware supported Compressed Textures
  11358. this._texturesSupported = new Array();
  11359. this._onVRFullScreenTriggered = function () {
  11360. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11361. //get the old size before we change
  11362. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11363. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11364. //get the width and height, change the render size
  11365. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11366. _this.setHardwareScalingLevel(1);
  11367. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11368. }
  11369. else {
  11370. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11371. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11372. }
  11373. };
  11374. this._boundUniforms = {};
  11375. // Register promises
  11376. BABYLON.PromisePolyfill.Apply();
  11377. var canvas = null;
  11378. Engine.Instances.push(this);
  11379. if (!canvasOrContext) {
  11380. return;
  11381. }
  11382. options = options || {};
  11383. if (canvasOrContext.getContext) {
  11384. canvas = canvasOrContext;
  11385. this._renderingCanvas = canvas;
  11386. if (antialias != null) {
  11387. options.antialias = antialias;
  11388. }
  11389. if (options.deterministicLockstep === undefined) {
  11390. options.deterministicLockstep = false;
  11391. }
  11392. if (options.lockstepMaxSteps === undefined) {
  11393. options.lockstepMaxSteps = 4;
  11394. }
  11395. if (options.preserveDrawingBuffer === undefined) {
  11396. options.preserveDrawingBuffer = false;
  11397. }
  11398. if (options.audioEngine === undefined) {
  11399. options.audioEngine = true;
  11400. }
  11401. if (options.stencil === undefined) {
  11402. options.stencil = true;
  11403. }
  11404. this._deterministicLockstep = options.deterministicLockstep;
  11405. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11406. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11407. // Exceptions
  11408. if (navigator && navigator.userAgent) {
  11409. var ua = navigator.userAgent;
  11410. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11411. var exception = _a[_i];
  11412. var key = exception.key;
  11413. var targets = exception.targets;
  11414. if (ua.indexOf(key) > -1) {
  11415. if (exception.capture && exception.captureConstraint) {
  11416. var capture = exception.capture;
  11417. var constraint = exception.captureConstraint;
  11418. var regex = new RegExp(capture);
  11419. var matches = regex.exec(ua);
  11420. if (matches && matches.length > 0) {
  11421. var capturedValue = parseInt(matches[matches.length - 1]);
  11422. if (capturedValue >= constraint) {
  11423. continue;
  11424. }
  11425. }
  11426. }
  11427. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11428. var target = targets_1[_b];
  11429. switch (target) {
  11430. case "uniformBuffer":
  11431. this.disableUniformBuffers = true;
  11432. break;
  11433. case "textureBindingOptimization":
  11434. this.disableTextureBindingOptimization = true;
  11435. break;
  11436. }
  11437. }
  11438. }
  11439. }
  11440. }
  11441. // GL
  11442. if (!options.disableWebGL2Support) {
  11443. try {
  11444. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11445. if (this._gl) {
  11446. this._webGLVersion = 2.0;
  11447. }
  11448. }
  11449. catch (e) {
  11450. // Do nothing
  11451. }
  11452. }
  11453. if (!this._gl) {
  11454. if (!canvas) {
  11455. throw new Error("The provided canvas is null or undefined.");
  11456. }
  11457. try {
  11458. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11459. }
  11460. catch (e) {
  11461. throw new Error("WebGL not supported");
  11462. }
  11463. }
  11464. if (!this._gl) {
  11465. throw new Error("WebGL not supported");
  11466. }
  11467. this._onCanvasFocus = function () {
  11468. _this.onCanvasFocusObservable.notifyObservers(_this);
  11469. };
  11470. this._onCanvasBlur = function () {
  11471. _this.onCanvasBlurObservable.notifyObservers(_this);
  11472. };
  11473. canvas.addEventListener("focus", this._onCanvasFocus);
  11474. canvas.addEventListener("blur", this._onCanvasBlur);
  11475. this._onBlur = function () {
  11476. if (_this.disablePerformanceMonitorInBackground) {
  11477. _this._performanceMonitor.disable();
  11478. }
  11479. _this._windowIsBackground = true;
  11480. };
  11481. this._onFocus = function () {
  11482. if (_this.disablePerformanceMonitorInBackground) {
  11483. _this._performanceMonitor.enable();
  11484. }
  11485. _this._windowIsBackground = false;
  11486. };
  11487. this._onCanvasPointerOut = function (ev) {
  11488. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11489. };
  11490. window.addEventListener("blur", this._onBlur);
  11491. window.addEventListener("focus", this._onFocus);
  11492. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11493. // Context lost
  11494. if (!this._doNotHandleContextLost) {
  11495. this._onContextLost = function (evt) {
  11496. evt.preventDefault();
  11497. _this._contextWasLost = true;
  11498. BABYLON.Tools.Warn("WebGL context lost.");
  11499. _this.onContextLostObservable.notifyObservers(_this);
  11500. };
  11501. this._onContextRestored = function (evt) {
  11502. // Adding a timeout to avoid race condition at browser level
  11503. setTimeout(function () {
  11504. // Rebuild gl context
  11505. _this._initGLContext();
  11506. // Rebuild effects
  11507. _this._rebuildEffects();
  11508. // Rebuild textures
  11509. _this._rebuildInternalTextures();
  11510. // Rebuild buffers
  11511. _this._rebuildBuffers();
  11512. // Cache
  11513. _this.wipeCaches(true);
  11514. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11515. _this.onContextRestoredObservable.notifyObservers(_this);
  11516. _this._contextWasLost = false;
  11517. }, 0);
  11518. };
  11519. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11520. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11521. }
  11522. }
  11523. else {
  11524. this._gl = canvasOrContext;
  11525. this._renderingCanvas = this._gl.canvas;
  11526. if (this._gl.renderbufferStorageMultisample) {
  11527. this._webGLVersion = 2.0;
  11528. }
  11529. options.stencil = this._gl.getContextAttributes().stencil;
  11530. }
  11531. // Viewport
  11532. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11533. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11534. this.resize();
  11535. this._isStencilEnable = options.stencil ? true : false;
  11536. this._initGLContext();
  11537. if (canvas) {
  11538. // Fullscreen
  11539. this._onFullscreenChange = function () {
  11540. if (document.fullscreen !== undefined) {
  11541. _this.isFullscreen = document.fullscreen;
  11542. }
  11543. else if (document.mozFullScreen !== undefined) {
  11544. _this.isFullscreen = document.mozFullScreen;
  11545. }
  11546. else if (document.webkitIsFullScreen !== undefined) {
  11547. _this.isFullscreen = document.webkitIsFullScreen;
  11548. }
  11549. else if (document.msIsFullScreen !== undefined) {
  11550. _this.isFullscreen = document.msIsFullScreen;
  11551. }
  11552. // Pointer lock
  11553. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11554. canvas.requestPointerLock = canvas.requestPointerLock ||
  11555. canvas.msRequestPointerLock ||
  11556. canvas.mozRequestPointerLock ||
  11557. canvas.webkitRequestPointerLock;
  11558. if (canvas.requestPointerLock) {
  11559. canvas.requestPointerLock();
  11560. }
  11561. }
  11562. };
  11563. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11564. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11565. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11566. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11567. // Pointer lock
  11568. this._onPointerLockChange = function () {
  11569. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11570. document.webkitPointerLockElement === canvas ||
  11571. document.msPointerLockElement === canvas ||
  11572. document.pointerLockElement === canvas);
  11573. };
  11574. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11575. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11576. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11577. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11578. this._onVRDisplayPointerRestricted = function () {
  11579. if (canvas) {
  11580. canvas.requestPointerLock();
  11581. }
  11582. };
  11583. this._onVRDisplayPointerUnrestricted = function () {
  11584. document.exitPointerLock();
  11585. };
  11586. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11587. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11588. }
  11589. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11590. Engine.audioEngine = new BABYLON.AudioEngine();
  11591. }
  11592. // Prepare buffer pointers
  11593. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11594. this._currentBufferPointers[i] = new BufferPointer();
  11595. }
  11596. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11597. // Load WebVR Devices
  11598. if (options.autoEnableWebVR) {
  11599. this.initWebVR();
  11600. }
  11601. // Detect if we are running on a faulty buggy OS.
  11602. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11603. // Detect if we are running on a faulty buggy desktop OS.
  11604. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11605. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11606. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11607. }
  11608. Object.defineProperty(Engine, "LastCreatedEngine", {
  11609. /**
  11610. * Gets the latest created engine
  11611. */
  11612. get: function () {
  11613. if (Engine.Instances.length === 0) {
  11614. return null;
  11615. }
  11616. return Engine.Instances[Engine.Instances.length - 1];
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Object.defineProperty(Engine, "LastCreatedScene", {
  11622. /**
  11623. * Gets the latest created scene
  11624. */
  11625. get: function () {
  11626. var lastCreatedEngine = Engine.LastCreatedEngine;
  11627. if (!lastCreatedEngine) {
  11628. return null;
  11629. }
  11630. if (lastCreatedEngine.scenes.length === 0) {
  11631. return null;
  11632. }
  11633. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. /**
  11639. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11640. * @param flag defines which part of the materials must be marked as dirty
  11641. * @param predicate defines a predicate used to filter which materials should be affected
  11642. */
  11643. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11644. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11645. var engine = Engine.Instances[engineIndex];
  11646. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11647. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11648. }
  11649. }
  11650. };
  11651. Object.defineProperty(Engine, "NEVER", {
  11652. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11653. get: function () {
  11654. return Engine._NEVER;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Engine, "ALWAYS", {
  11660. /** 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 */
  11661. get: function () {
  11662. return Engine._ALWAYS;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine, "LESS", {
  11668. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11669. get: function () {
  11670. return Engine._LESS;
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(Engine, "EQUAL", {
  11676. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11677. get: function () {
  11678. return Engine._EQUAL;
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(Engine, "LEQUAL", {
  11684. /** 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 */
  11685. get: function () {
  11686. return Engine._LEQUAL;
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Engine, "GREATER", {
  11692. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11693. get: function () {
  11694. return Engine._GREATER;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "GEQUAL", {
  11700. /** 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 */
  11701. get: function () {
  11702. return Engine._GEQUAL;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(Engine, "NOTEQUAL", {
  11708. /** 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 */
  11709. get: function () {
  11710. return Engine._NOTEQUAL;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "KEEP", {
  11716. /** Passed to stencilOperation to specify that stencil value must be kept */
  11717. get: function () {
  11718. return Engine._KEEP;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(Engine, "REPLACE", {
  11724. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11725. get: function () {
  11726. return Engine._REPLACE;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "INCR", {
  11732. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11733. get: function () {
  11734. return Engine._INCR;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "DECR", {
  11740. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11741. get: function () {
  11742. return Engine._DECR;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "INVERT", {
  11748. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11749. get: function () {
  11750. return Engine._INVERT;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "INCR_WRAP", {
  11756. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11757. get: function () {
  11758. return Engine._INCR_WRAP;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "DECR_WRAP", {
  11764. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11765. get: function () {
  11766. return Engine._DECR_WRAP;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11772. // Alpha
  11773. /** Defines that alpha blending is disabled */
  11774. get: function () {
  11775. return Engine._ALPHA_DISABLE;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11781. /** Defines that alpha blending to SRC + DEST */
  11782. get: function () {
  11783. return Engine._ALPHA_ONEONE;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "ALPHA_ADD", {
  11789. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11790. get: function () {
  11791. return Engine._ALPHA_ADD;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11797. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11798. get: function () {
  11799. return Engine._ALPHA_COMBINE;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11805. /** Defines that alpha blending to DEST - SRC * DEST */
  11806. get: function () {
  11807. return Engine._ALPHA_SUBTRACT;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11813. /** Defines that alpha blending to SRC * DEST */
  11814. get: function () {
  11815. return Engine._ALPHA_MULTIPLY;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11821. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11822. get: function () {
  11823. return Engine._ALPHA_MAXIMIZED;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11829. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11830. get: function () {
  11831. return Engine._ALPHA_PREMULTIPLIED;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11837. /**
  11838. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11839. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11840. */
  11841. get: function () {
  11842. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11848. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11849. get: function () {
  11850. return Engine._ALPHA_INTERPOLATE;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11856. /**
  11857. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11858. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11859. */
  11860. get: function () {
  11861. return Engine._ALPHA_SCREENMODE;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11867. // Delays
  11868. /** Defines that the ressource is not delayed*/
  11869. get: function () {
  11870. return Engine._DELAYLOADSTATE_NONE;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11876. /** Defines that the ressource was successfully delay loaded */
  11877. get: function () {
  11878. return Engine._DELAYLOADSTATE_LOADED;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11884. /** Defines that the ressource is currently delay loading */
  11885. get: function () {
  11886. return Engine._DELAYLOADSTATE_LOADING;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11892. /** Defines that the ressource is delayed and has not started loading */
  11893. get: function () {
  11894. return Engine._DELAYLOADSTATE_NOTLOADED;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11900. /** ALPHA */
  11901. get: function () {
  11902. return Engine._TEXTUREFORMAT_ALPHA;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11908. /** LUMINANCE */
  11909. get: function () {
  11910. return Engine._TEXTUREFORMAT_LUMINANCE;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11916. /**
  11917. * R32F
  11918. */
  11919. get: function () {
  11920. return Engine._TEXTUREFORMAT_R32F;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11926. /**
  11927. * RG32F
  11928. */
  11929. get: function () {
  11930. return Engine._TEXTUREFORMAT_RG32F;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11936. /**
  11937. * RGB32F
  11938. */
  11939. get: function () {
  11940. return Engine._TEXTUREFORMAT_RGB32F;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11946. /**
  11947. * RGBA32F
  11948. */
  11949. get: function () {
  11950. return Engine._TEXTUREFORMAT_RGBA32F;
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11956. /** LUMINANCE_ALPHA */
  11957. get: function () {
  11958. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11964. /** RGB */
  11965. get: function () {
  11966. return Engine._TEXTUREFORMAT_RGB;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11972. /** RGBA */
  11973. get: function () {
  11974. return Engine._TEXTUREFORMAT_RGBA;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11980. /** UNSIGNED_INT */
  11981. get: function () {
  11982. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11988. /** FLOAT */
  11989. get: function () {
  11990. return Engine._TEXTURETYPE_FLOAT;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11996. /** HALF_FLOAT */
  11997. get: function () {
  11998. return Engine._TEXTURETYPE_HALF_FLOAT;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12004. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12005. get: function () {
  12006. return Engine._SCALEMODE_FLOOR;
  12007. },
  12008. enumerable: true,
  12009. configurable: true
  12010. });
  12011. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12012. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12013. get: function () {
  12014. return Engine._SCALEMODE_NEAREST;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12020. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12021. get: function () {
  12022. return Engine._SCALEMODE_CEILING;
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Engine, "Version", {
  12028. /**
  12029. * Returns the current version of the framework
  12030. */
  12031. get: function () {
  12032. return "3.3.0-alpha.0";
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12038. /**
  12039. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12040. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12041. */
  12042. get: function () {
  12043. return this._vrExclusivePointerMode;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12049. /**
  12050. * Gets a boolean indicating that the engine supports uniform buffers
  12051. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12052. */
  12053. get: function () {
  12054. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12060. /**
  12061. * Gets a boolean indicating that only power of 2 textures are supported
  12062. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12063. */
  12064. get: function () {
  12065. return this._webGLVersion < 2 || this.forcePOTTextures;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12071. /**
  12072. * Gets the performance monitor attached to this engine
  12073. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12074. */
  12075. get: function () {
  12076. return this._performanceMonitor;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12082. /**
  12083. * Gets the list of texture formats supported
  12084. */
  12085. get: function () {
  12086. return this._texturesSupported;
  12087. },
  12088. enumerable: true,
  12089. configurable: true
  12090. });
  12091. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12092. /**
  12093. * Gets the list of texture formats in use
  12094. */
  12095. get: function () {
  12096. return this._textureFormatInUse;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Object.defineProperty(Engine.prototype, "currentViewport", {
  12102. /**
  12103. * Gets the current viewport
  12104. */
  12105. get: function () {
  12106. return this._cachedViewport;
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12112. /**
  12113. * Gets the default empty texture
  12114. */
  12115. get: function () {
  12116. if (!this._emptyTexture) {
  12117. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12118. }
  12119. return this._emptyTexture;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12125. /**
  12126. * Gets the default empty 3D texture
  12127. */
  12128. get: function () {
  12129. if (!this._emptyTexture3D) {
  12130. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12131. }
  12132. return this._emptyTexture3D;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12138. /**
  12139. * Gets the default empty cube texture
  12140. */
  12141. get: function () {
  12142. if (!this._emptyCubeTexture) {
  12143. var faceData = new Uint8Array(4);
  12144. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12145. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12146. }
  12147. return this._emptyCubeTexture;
  12148. },
  12149. enumerable: true,
  12150. configurable: true
  12151. });
  12152. Engine.prototype._rebuildInternalTextures = function () {
  12153. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12154. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12155. var internalTexture = currentState_1[_i];
  12156. internalTexture._rebuild();
  12157. }
  12158. };
  12159. Engine.prototype._rebuildEffects = function () {
  12160. for (var key in this._compiledEffects) {
  12161. var effect = this._compiledEffects[key];
  12162. effect._prepareEffect();
  12163. }
  12164. BABYLON.Effect.ResetCache();
  12165. };
  12166. Engine.prototype._rebuildBuffers = function () {
  12167. // Index / Vertex
  12168. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12169. var scene = _a[_i];
  12170. scene.resetCachedMaterial();
  12171. scene._rebuildGeometries();
  12172. scene._rebuildTextures();
  12173. }
  12174. // Uniforms
  12175. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12176. var uniformBuffer = _c[_b];
  12177. uniformBuffer._rebuild();
  12178. }
  12179. };
  12180. Engine.prototype._initGLContext = function () {
  12181. // Caps
  12182. this._caps = new EngineCapabilities();
  12183. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12184. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12185. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12186. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12187. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12188. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12189. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12190. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12191. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12192. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12193. // Infos
  12194. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12195. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12196. if (rendererInfo != null) {
  12197. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12198. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12199. }
  12200. if (!this._glVendor) {
  12201. this._glVendor = "Unknown vendor";
  12202. }
  12203. if (!this._glRenderer) {
  12204. this._glRenderer = "Unknown renderer";
  12205. }
  12206. // Constants
  12207. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12208. if (this._gl.RGBA16F !== 0x881A) {
  12209. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12210. }
  12211. if (this._gl.RGBA32F !== 0x8814) {
  12212. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12213. }
  12214. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12215. this._gl.DEPTH24_STENCIL8 = 35056;
  12216. }
  12217. // Extensions
  12218. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12219. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12220. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12221. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12222. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12223. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12224. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12225. 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');
  12226. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12227. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12228. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12229. this._caps.highPrecisionShaderSupported = true;
  12230. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12231. if (this._caps.timerQuery) {
  12232. if (this._webGLVersion === 1) {
  12233. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12234. }
  12235. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12236. }
  12237. // Checks if some of the format renders first to allow the use of webgl inspector.
  12238. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12239. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12240. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12241. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12242. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12243. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12244. if (this._webGLVersion > 1) {
  12245. this._gl.HALF_FLOAT_OES = 0x140B;
  12246. }
  12247. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12248. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12249. // Draw buffers
  12250. if (this._webGLVersion > 1) {
  12251. this._caps.drawBuffersExtension = true;
  12252. }
  12253. else {
  12254. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12255. if (drawBuffersExtension !== null) {
  12256. this._caps.drawBuffersExtension = true;
  12257. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12258. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12259. for (var i = 0; i < 16; i++) {
  12260. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12261. }
  12262. }
  12263. else {
  12264. this._caps.drawBuffersExtension = false;
  12265. }
  12266. }
  12267. // Depth Texture
  12268. if (this._webGLVersion > 1) {
  12269. this._caps.depthTextureExtension = true;
  12270. }
  12271. else {
  12272. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12273. if (depthTextureExtension != null) {
  12274. this._caps.depthTextureExtension = true;
  12275. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12276. }
  12277. }
  12278. // Vertex array object
  12279. if (this._webGLVersion > 1) {
  12280. this._caps.vertexArrayObject = true;
  12281. }
  12282. else {
  12283. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12284. if (vertexArrayObjectExtension != null) {
  12285. this._caps.vertexArrayObject = true;
  12286. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12287. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12288. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12289. }
  12290. else {
  12291. this._caps.vertexArrayObject = false;
  12292. }
  12293. }
  12294. // Instances count
  12295. if (this._webGLVersion > 1) {
  12296. this._caps.instancedArrays = true;
  12297. }
  12298. else {
  12299. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12300. if (instanceExtension != null) {
  12301. this._caps.instancedArrays = true;
  12302. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12303. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12304. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12305. }
  12306. else {
  12307. this._caps.instancedArrays = false;
  12308. }
  12309. }
  12310. // Intelligently add supported compressed formats in order to check for.
  12311. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12312. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12313. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12314. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12315. if (this._caps.astc)
  12316. this.texturesSupported.push('-astc.ktx');
  12317. if (this._caps.s3tc)
  12318. this.texturesSupported.push('-dxt.ktx');
  12319. if (this._caps.pvrtc)
  12320. this.texturesSupported.push('-pvrtc.ktx');
  12321. if (this._caps.etc2)
  12322. this.texturesSupported.push('-etc2.ktx');
  12323. if (this._caps.etc1)
  12324. this.texturesSupported.push('-etc1.ktx');
  12325. if (this._gl.getShaderPrecisionFormat) {
  12326. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12327. if (highp) {
  12328. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12329. }
  12330. }
  12331. // Depth buffer
  12332. this.setDepthBuffer(true);
  12333. this.setDepthFunctionToLessOrEqual();
  12334. this.setDepthWrite(true);
  12335. // Texture maps
  12336. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12337. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12338. this._nextFreeTextureSlots.push(slot);
  12339. }
  12340. };
  12341. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12342. /**
  12343. * Gets version of the current webGL context
  12344. */
  12345. get: function () {
  12346. return this._webGLVersion;
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12352. /**
  12353. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12354. */
  12355. get: function () {
  12356. return this._isStencilEnable;
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. Engine.prototype._prepareWorkingCanvas = function () {
  12362. if (this._workingCanvas) {
  12363. return;
  12364. }
  12365. this._workingCanvas = document.createElement("canvas");
  12366. var context = this._workingCanvas.getContext("2d");
  12367. if (context) {
  12368. this._workingContext = context;
  12369. }
  12370. };
  12371. /**
  12372. * Reset the texture cache to empty state
  12373. */
  12374. Engine.prototype.resetTextureCache = function () {
  12375. for (var key in this._boundTexturesCache) {
  12376. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12377. continue;
  12378. }
  12379. var boundTexture = this._boundTexturesCache[key];
  12380. if (boundTexture) {
  12381. this._removeDesignatedSlot(boundTexture);
  12382. }
  12383. this._boundTexturesCache[key] = null;
  12384. }
  12385. if (!this.disableTextureBindingOptimization) {
  12386. this._nextFreeTextureSlots = [];
  12387. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12388. this._nextFreeTextureSlots.push(slot);
  12389. }
  12390. }
  12391. this._currentTextureChannel = -1;
  12392. };
  12393. /**
  12394. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12395. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12396. * @returns true if engine is in deterministic lock step mode
  12397. */
  12398. Engine.prototype.isDeterministicLockStep = function () {
  12399. return this._deterministicLockstep;
  12400. };
  12401. /**
  12402. * Gets the max steps when engine is running in deterministic lock step
  12403. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12404. * @returns the max steps
  12405. */
  12406. Engine.prototype.getLockstepMaxSteps = function () {
  12407. return this._lockstepMaxSteps;
  12408. };
  12409. /**
  12410. * Gets an object containing information about the current webGL context
  12411. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12412. */
  12413. Engine.prototype.getGlInfo = function () {
  12414. return {
  12415. vendor: this._glVendor,
  12416. renderer: this._glRenderer,
  12417. version: this._glVersion
  12418. };
  12419. };
  12420. /**
  12421. * Gets current aspect ratio
  12422. * @param camera defines the camera to use to get the aspect ratio
  12423. * @param useScreen defines if screen size must be used (or the current render target if any)
  12424. * @returns a number defining the aspect ratio
  12425. */
  12426. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12427. if (useScreen === void 0) { useScreen = false; }
  12428. var viewport = camera.viewport;
  12429. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12430. };
  12431. /**
  12432. * Gets current screen aspect ratio
  12433. * @returns a number defining the aspect ratio
  12434. */
  12435. Engine.prototype.getScreenAspectRatio = function () {
  12436. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12437. };
  12438. /**
  12439. * Gets the current render width
  12440. * @param useScreen defines if screen size must be used (or the current render target if any)
  12441. * @returns a number defining the current render width
  12442. */
  12443. Engine.prototype.getRenderWidth = function (useScreen) {
  12444. if (useScreen === void 0) { useScreen = false; }
  12445. if (!useScreen && this._currentRenderTarget) {
  12446. return this._currentRenderTarget.width;
  12447. }
  12448. return this._gl.drawingBufferWidth;
  12449. };
  12450. /**
  12451. * Gets the current render height
  12452. * @param useScreen defines if screen size must be used (or the current render target if any)
  12453. * @returns a number defining the current render height
  12454. */
  12455. Engine.prototype.getRenderHeight = function (useScreen) {
  12456. if (useScreen === void 0) { useScreen = false; }
  12457. if (!useScreen && this._currentRenderTarget) {
  12458. return this._currentRenderTarget.height;
  12459. }
  12460. return this._gl.drawingBufferHeight;
  12461. };
  12462. /**
  12463. * Gets the HTML canvas attached with the current webGL context
  12464. * @returns a HTML canvas
  12465. */
  12466. Engine.prototype.getRenderingCanvas = function () {
  12467. return this._renderingCanvas;
  12468. };
  12469. /**
  12470. * Gets the client rect of the HTML canvas attached with the current webGL context
  12471. * @returns a client rectanglee
  12472. */
  12473. Engine.prototype.getRenderingCanvasClientRect = function () {
  12474. if (!this._renderingCanvas) {
  12475. return null;
  12476. }
  12477. return this._renderingCanvas.getBoundingClientRect();
  12478. };
  12479. /**
  12480. * Defines the hardware scaling level.
  12481. * By default the hardware scaling level is computed from the window device ratio.
  12482. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12483. * @param level defines the level to use
  12484. */
  12485. Engine.prototype.setHardwareScalingLevel = function (level) {
  12486. this._hardwareScalingLevel = level;
  12487. this.resize();
  12488. };
  12489. /**
  12490. * Gets the current hardware scaling level.
  12491. * By default the hardware scaling level is computed from the window device ratio.
  12492. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12493. * @returns a number indicating the current hardware scaling level
  12494. */
  12495. Engine.prototype.getHardwareScalingLevel = function () {
  12496. return this._hardwareScalingLevel;
  12497. };
  12498. /**
  12499. * Gets the list of loaded textures
  12500. * @returns an array containing all loaded textures
  12501. */
  12502. Engine.prototype.getLoadedTexturesCache = function () {
  12503. return this._internalTexturesCache;
  12504. };
  12505. /**
  12506. * Gets the object containing all engine capabilities
  12507. * @returns the EngineCapabilities object
  12508. */
  12509. Engine.prototype.getCaps = function () {
  12510. return this._caps;
  12511. };
  12512. Object.defineProperty(Engine.prototype, "drawCalls", {
  12513. /** @hidden */
  12514. get: function () {
  12515. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12516. return 0;
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12522. /** @hidden */
  12523. get: function () {
  12524. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12525. return null;
  12526. },
  12527. enumerable: true,
  12528. configurable: true
  12529. });
  12530. /**
  12531. * Gets the current depth function
  12532. * @returns a number defining the depth function
  12533. */
  12534. Engine.prototype.getDepthFunction = function () {
  12535. return this._depthCullingState.depthFunc;
  12536. };
  12537. /**
  12538. * Sets the current depth function
  12539. * @param depthFunc defines the function to use
  12540. */
  12541. Engine.prototype.setDepthFunction = function (depthFunc) {
  12542. this._depthCullingState.depthFunc = depthFunc;
  12543. };
  12544. /**
  12545. * Sets the current depth function to GREATER
  12546. */
  12547. Engine.prototype.setDepthFunctionToGreater = function () {
  12548. this._depthCullingState.depthFunc = this._gl.GREATER;
  12549. };
  12550. /**
  12551. * Sets the current depth function to GEQUAL
  12552. */
  12553. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12554. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12555. };
  12556. /**
  12557. * Sets the current depth function to LESS
  12558. */
  12559. Engine.prototype.setDepthFunctionToLess = function () {
  12560. this._depthCullingState.depthFunc = this._gl.LESS;
  12561. };
  12562. /**
  12563. * Sets the current depth function to LEQUAL
  12564. */
  12565. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12566. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12567. };
  12568. /**
  12569. * Gets a boolean indicating if stencil buffer is enabled
  12570. * @returns the current stencil buffer state
  12571. */
  12572. Engine.prototype.getStencilBuffer = function () {
  12573. return this._stencilState.stencilTest;
  12574. };
  12575. /**
  12576. * Enable or disable the stencil buffer
  12577. * @param enable defines if the stencil buffer must be enabled or disabled
  12578. */
  12579. Engine.prototype.setStencilBuffer = function (enable) {
  12580. this._stencilState.stencilTest = enable;
  12581. };
  12582. /**
  12583. * Gets the current stencil mask
  12584. * @returns a number defining the new stencil mask to use
  12585. */
  12586. Engine.prototype.getStencilMask = function () {
  12587. return this._stencilState.stencilMask;
  12588. };
  12589. /**
  12590. * Sets the current stencil mask
  12591. * @param mask defines the new stencil mask to use
  12592. */
  12593. Engine.prototype.setStencilMask = function (mask) {
  12594. this._stencilState.stencilMask = mask;
  12595. };
  12596. /**
  12597. * Gets the current stencil function
  12598. * @returns a number defining the stencil function to use
  12599. */
  12600. Engine.prototype.getStencilFunction = function () {
  12601. return this._stencilState.stencilFunc;
  12602. };
  12603. /**
  12604. * Gets the current stencil reference value
  12605. * @returns a number defining the stencil reference value to use
  12606. */
  12607. Engine.prototype.getStencilFunctionReference = function () {
  12608. return this._stencilState.stencilFuncRef;
  12609. };
  12610. /**
  12611. * Gets the current stencil mask
  12612. * @returns a number defining the stencil mask to use
  12613. */
  12614. Engine.prototype.getStencilFunctionMask = function () {
  12615. return this._stencilState.stencilFuncMask;
  12616. };
  12617. /**
  12618. * Sets the current stencil function
  12619. * @param stencilFunc defines the new stencil function to use
  12620. */
  12621. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12622. this._stencilState.stencilFunc = stencilFunc;
  12623. };
  12624. /**
  12625. * Sets the current stencil reference
  12626. * @param reference defines the new stencil reference to use
  12627. */
  12628. Engine.prototype.setStencilFunctionReference = function (reference) {
  12629. this._stencilState.stencilFuncRef = reference;
  12630. };
  12631. /**
  12632. * Sets the current stencil mask
  12633. * @param mask defines the new stencil mask to use
  12634. */
  12635. Engine.prototype.setStencilFunctionMask = function (mask) {
  12636. this._stencilState.stencilFuncMask = mask;
  12637. };
  12638. /**
  12639. * Gets the current stencil operation when stencil fails
  12640. * @returns a number defining stencil operation to use when stencil fails
  12641. */
  12642. Engine.prototype.getStencilOperationFail = function () {
  12643. return this._stencilState.stencilOpStencilFail;
  12644. };
  12645. /**
  12646. * Gets the current stencil operation when depth fails
  12647. * @returns a number defining stencil operation to use when depth fails
  12648. */
  12649. Engine.prototype.getStencilOperationDepthFail = function () {
  12650. return this._stencilState.stencilOpDepthFail;
  12651. };
  12652. /**
  12653. * Gets the current stencil operation when stencil passes
  12654. * @returns a number defining stencil operation to use when stencil passes
  12655. */
  12656. Engine.prototype.getStencilOperationPass = function () {
  12657. return this._stencilState.stencilOpStencilDepthPass;
  12658. };
  12659. /**
  12660. * Sets the stencil operation to use when stencil fails
  12661. * @param operation defines the stencil operation to use when stencil fails
  12662. */
  12663. Engine.prototype.setStencilOperationFail = function (operation) {
  12664. this._stencilState.stencilOpStencilFail = operation;
  12665. };
  12666. /**
  12667. * Sets the stencil operation to use when depth fails
  12668. * @param operation defines the stencil operation to use when depth fails
  12669. */
  12670. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12671. this._stencilState.stencilOpDepthFail = operation;
  12672. };
  12673. /**
  12674. * Sets the stencil operation to use when stencil passes
  12675. * @param operation defines the stencil operation to use when stencil passes
  12676. */
  12677. Engine.prototype.setStencilOperationPass = function (operation) {
  12678. this._stencilState.stencilOpStencilDepthPass = operation;
  12679. };
  12680. /**
  12681. * Sets a boolean indicating if the dithering state is enabled or disabled
  12682. * @param value defines the dithering state
  12683. */
  12684. Engine.prototype.setDitheringState = function (value) {
  12685. if (value) {
  12686. this._gl.enable(this._gl.DITHER);
  12687. }
  12688. else {
  12689. this._gl.disable(this._gl.DITHER);
  12690. }
  12691. };
  12692. /**
  12693. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12694. * @param value defines the rasterizer state
  12695. */
  12696. Engine.prototype.setRasterizerState = function (value) {
  12697. if (value) {
  12698. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12699. }
  12700. else {
  12701. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12702. }
  12703. };
  12704. /**
  12705. * stop executing a render loop function and remove it from the execution array
  12706. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12707. */
  12708. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12709. if (!renderFunction) {
  12710. this._activeRenderLoops = [];
  12711. return;
  12712. }
  12713. var index = this._activeRenderLoops.indexOf(renderFunction);
  12714. if (index >= 0) {
  12715. this._activeRenderLoops.splice(index, 1);
  12716. }
  12717. };
  12718. /** @hidden */
  12719. Engine.prototype._renderLoop = function () {
  12720. if (!this._contextWasLost) {
  12721. var shouldRender = true;
  12722. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12723. shouldRender = false;
  12724. }
  12725. if (shouldRender) {
  12726. // Start new frame
  12727. this.beginFrame();
  12728. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12729. var renderFunction = this._activeRenderLoops[index];
  12730. renderFunction();
  12731. }
  12732. // Present
  12733. this.endFrame();
  12734. }
  12735. }
  12736. if (this._activeRenderLoops.length > 0) {
  12737. // Register new frame
  12738. var requester = null;
  12739. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12740. requester = this._vrDisplay;
  12741. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12742. }
  12743. else {
  12744. this._renderingQueueLaunched = false;
  12745. }
  12746. };
  12747. /**
  12748. * Register and execute a render loop. The engine can have more than one render function
  12749. * @param renderFunction defines the function to continuously execute
  12750. */
  12751. Engine.prototype.runRenderLoop = function (renderFunction) {
  12752. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12753. return;
  12754. }
  12755. this._activeRenderLoops.push(renderFunction);
  12756. if (!this._renderingQueueLaunched) {
  12757. this._renderingQueueLaunched = true;
  12758. this._bindedRenderFunction = this._renderLoop.bind(this);
  12759. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12760. }
  12761. };
  12762. /**
  12763. * Toggle full screen mode
  12764. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12765. * @param options defines an option object to be sent to the requestFullscreen function
  12766. */
  12767. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12768. if (this.isFullscreen) {
  12769. BABYLON.Tools.ExitFullscreen();
  12770. }
  12771. else {
  12772. this._pointerLockRequested = requestPointerLock;
  12773. if (this._renderingCanvas) {
  12774. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12775. }
  12776. }
  12777. };
  12778. /**
  12779. * Clear the current render buffer or the current render target (if any is set up)
  12780. * @param color defines the color to use
  12781. * @param backBuffer defines if the back buffer must be cleared
  12782. * @param depth defines if the depth buffer must be cleared
  12783. * @param stencil defines if the stencil buffer must be cleared
  12784. */
  12785. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12786. if (stencil === void 0) { stencil = false; }
  12787. this.applyStates();
  12788. var mode = 0;
  12789. if (backBuffer && color) {
  12790. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12791. mode |= this._gl.COLOR_BUFFER_BIT;
  12792. }
  12793. if (depth) {
  12794. this._gl.clearDepth(1.0);
  12795. mode |= this._gl.DEPTH_BUFFER_BIT;
  12796. }
  12797. if (stencil) {
  12798. this._gl.clearStencil(0);
  12799. mode |= this._gl.STENCIL_BUFFER_BIT;
  12800. }
  12801. this._gl.clear(mode);
  12802. };
  12803. /**
  12804. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12805. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12806. * @param y defines the y-coordinate of the corner of the clear rectangle
  12807. * @param width defines the width of the clear rectangle
  12808. * @param height defines the height of the clear rectangle
  12809. * @param clearColor defines the clear color
  12810. */
  12811. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12812. var gl = this._gl;
  12813. // Save state
  12814. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12815. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12816. // Change state
  12817. gl.enable(gl.SCISSOR_TEST);
  12818. gl.scissor(x, y, width, height);
  12819. // Clear
  12820. this.clear(clearColor, true, true, true);
  12821. // Restore state
  12822. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12823. if (curScissor === true) {
  12824. gl.enable(gl.SCISSOR_TEST);
  12825. }
  12826. else {
  12827. gl.disable(gl.SCISSOR_TEST);
  12828. }
  12829. };
  12830. /**
  12831. * Set the WebGL's viewport
  12832. * @param viewport defines the viewport element to be used
  12833. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12834. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12835. */
  12836. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12837. var width = requiredWidth || this.getRenderWidth();
  12838. var height = requiredHeight || this.getRenderHeight();
  12839. var x = viewport.x || 0;
  12840. var y = viewport.y || 0;
  12841. this._cachedViewport = viewport;
  12842. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12843. };
  12844. /**
  12845. * Directly set the WebGL Viewport
  12846. * @param x defines the x coordinate of the viewport (in screen space)
  12847. * @param y defines the y coordinate of the viewport (in screen space)
  12848. * @param width defines the width of the viewport (in screen space)
  12849. * @param height defines the height of the viewport (in screen space)
  12850. * @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
  12851. */
  12852. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12853. var currentViewport = this._cachedViewport;
  12854. this._cachedViewport = null;
  12855. this._gl.viewport(x, y, width, height);
  12856. return currentViewport;
  12857. };
  12858. /**
  12859. * Begin a new frame
  12860. */
  12861. Engine.prototype.beginFrame = function () {
  12862. this.onBeginFrameObservable.notifyObservers(this);
  12863. this._measureFps();
  12864. };
  12865. /**
  12866. * Enf the current frame
  12867. */
  12868. Engine.prototype.endFrame = function () {
  12869. // Force a flush in case we are using a bad OS.
  12870. if (this._badOS) {
  12871. this.flushFramebuffer();
  12872. }
  12873. // Submit frame to the vr device, if enabled
  12874. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12875. // TODO: We should only submit the frame if we read frameData successfully.
  12876. this._vrDisplay.submitFrame();
  12877. }
  12878. this.onEndFrameObservable.notifyObservers(this);
  12879. };
  12880. /**
  12881. * Resize the view according to the canvas' size
  12882. */
  12883. Engine.prototype.resize = function () {
  12884. // We're not resizing the size of the canvas while in VR mode & presenting
  12885. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12886. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12887. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12888. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12889. }
  12890. };
  12891. /**
  12892. * Force a specific size of the canvas
  12893. * @param width defines the new canvas' width
  12894. * @param height defines the new canvas' height
  12895. */
  12896. Engine.prototype.setSize = function (width, height) {
  12897. if (!this._renderingCanvas) {
  12898. return;
  12899. }
  12900. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12901. return;
  12902. }
  12903. this._renderingCanvas.width = width;
  12904. this._renderingCanvas.height = height;
  12905. for (var index = 0; index < this.scenes.length; index++) {
  12906. var scene = this.scenes[index];
  12907. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12908. var cam = scene.cameras[camIndex];
  12909. cam._currentRenderId = 0;
  12910. }
  12911. }
  12912. if (this.onResizeObservable.hasObservers) {
  12913. this.onResizeObservable.notifyObservers(this);
  12914. }
  12915. };
  12916. // WebVR functions
  12917. /**
  12918. * Gets a boolean indicating if a webVR device was detected
  12919. * @returns true if a webVR device was detected
  12920. */
  12921. Engine.prototype.isVRDevicePresent = function () {
  12922. return !!this._vrDisplay;
  12923. };
  12924. /**
  12925. * Gets the current webVR device
  12926. * @returns the current webVR device (or null)
  12927. */
  12928. Engine.prototype.getVRDevice = function () {
  12929. return this._vrDisplay;
  12930. };
  12931. /**
  12932. * Initializes a webVR display and starts listening to display change events
  12933. * The onVRDisplayChangedObservable will be notified upon these changes
  12934. * @returns The onVRDisplayChangedObservable
  12935. */
  12936. Engine.prototype.initWebVR = function () {
  12937. this.initWebVRAsync();
  12938. return this.onVRDisplayChangedObservable;
  12939. };
  12940. /**
  12941. * Initializes a webVR display and starts listening to display change events
  12942. * The onVRDisplayChangedObservable will be notified upon these changes
  12943. * @returns A promise containing a VRDisplay and if vr is supported
  12944. */
  12945. Engine.prototype.initWebVRAsync = function () {
  12946. var _this = this;
  12947. var notifyObservers = function () {
  12948. var eventArgs = {
  12949. vrDisplay: _this._vrDisplay,
  12950. vrSupported: _this._vrSupported
  12951. };
  12952. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12953. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12954. };
  12955. if (!this._onVrDisplayConnect) {
  12956. this._onVrDisplayConnect = function (event) {
  12957. _this._vrDisplay = event.display;
  12958. notifyObservers();
  12959. };
  12960. this._onVrDisplayDisconnect = function () {
  12961. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12962. _this._vrDisplay = undefined;
  12963. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12964. notifyObservers();
  12965. };
  12966. this._onVrDisplayPresentChange = function () {
  12967. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12968. };
  12969. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12970. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12971. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12972. }
  12973. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12974. this._webVRInitPromise.then(notifyObservers);
  12975. return this._webVRInitPromise;
  12976. };
  12977. /**
  12978. * Call this function to switch to webVR mode
  12979. * Will do nothing if webVR is not supported or if there is no webVR device
  12980. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12981. */
  12982. Engine.prototype.enableVR = function () {
  12983. var _this = this;
  12984. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12985. var onResolved = function () {
  12986. _this.onVRRequestPresentComplete.notifyObservers(true);
  12987. _this._onVRFullScreenTriggered();
  12988. };
  12989. var onRejected = function () {
  12990. _this.onVRRequestPresentComplete.notifyObservers(false);
  12991. };
  12992. this.onVRRequestPresentStart.notifyObservers(this);
  12993. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12994. }
  12995. };
  12996. /**
  12997. * Call this function to leave webVR mode
  12998. * Will do nothing if webVR is not supported or if there is no webVR device
  12999. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13000. */
  13001. Engine.prototype.disableVR = function () {
  13002. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13003. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13004. }
  13005. };
  13006. Engine.prototype._getVRDisplaysAsync = function () {
  13007. var _this = this;
  13008. return new Promise(function (res, rej) {
  13009. if (navigator.getVRDisplays) {
  13010. navigator.getVRDisplays().then(function (devices) {
  13011. _this._vrSupported = true;
  13012. // note that devices may actually be an empty array. This is fine;
  13013. // we expect this._vrDisplay to be undefined in this case.
  13014. _this._vrDisplay = devices[0];
  13015. res({
  13016. vrDisplay: _this._vrDisplay,
  13017. vrSupported: _this._vrSupported
  13018. });
  13019. });
  13020. }
  13021. else {
  13022. _this._vrDisplay = undefined;
  13023. _this._vrSupported = false;
  13024. res({
  13025. vrDisplay: _this._vrDisplay,
  13026. vrSupported: _this._vrSupported
  13027. });
  13028. }
  13029. });
  13030. };
  13031. /**
  13032. * Binds the frame buffer to the specified texture.
  13033. * @param texture The texture to render to or null for the default canvas
  13034. * @param faceIndex The face of the texture to render to in case of cube texture
  13035. * @param requiredWidth The width of the target to render to
  13036. * @param requiredHeight The height of the target to render to
  13037. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13038. * @param depthStencilTexture The depth stencil texture to use to render
  13039. */
  13040. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13041. if (this._currentRenderTarget) {
  13042. this.unBindFramebuffer(this._currentRenderTarget);
  13043. }
  13044. this._currentRenderTarget = texture;
  13045. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13046. var gl = this._gl;
  13047. if (texture.isCube) {
  13048. if (faceIndex === undefined) {
  13049. faceIndex = 0;
  13050. }
  13051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13052. if (depthStencilTexture) {
  13053. if (depthStencilTexture._generateStencilBuffer) {
  13054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13055. }
  13056. else {
  13057. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13058. }
  13059. }
  13060. }
  13061. if (this._cachedViewport && !forceFullscreenViewport) {
  13062. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13063. }
  13064. else {
  13065. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13066. }
  13067. this.wipeCaches();
  13068. };
  13069. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13070. if (this._currentFramebuffer !== framebuffer) {
  13071. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13072. this._currentFramebuffer = framebuffer;
  13073. }
  13074. };
  13075. /**
  13076. * Unbind the current render target texture from the webGL context
  13077. * @param texture defines the render target texture to unbind
  13078. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13079. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13080. */
  13081. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13082. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13083. this._currentRenderTarget = null;
  13084. // If MSAA, we need to bitblt back to main texture
  13085. var gl = this._gl;
  13086. if (texture._MSAAFramebuffer) {
  13087. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13088. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13089. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13090. }
  13091. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13092. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13093. gl.generateMipmap(gl.TEXTURE_2D);
  13094. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13095. }
  13096. if (onBeforeUnbind) {
  13097. if (texture._MSAAFramebuffer) {
  13098. // Bind the correct framebuffer
  13099. this.bindUnboundFramebuffer(texture._framebuffer);
  13100. }
  13101. onBeforeUnbind();
  13102. }
  13103. this.bindUnboundFramebuffer(null);
  13104. };
  13105. /**
  13106. * Unbind a list of render target textures from the webGL context
  13107. * This is used only when drawBuffer extension or webGL2 are active
  13108. * @param textures defines the render target textures to unbind
  13109. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13110. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13111. */
  13112. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13113. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13114. this._currentRenderTarget = null;
  13115. // If MSAA, we need to bitblt back to main texture
  13116. var gl = this._gl;
  13117. if (textures[0]._MSAAFramebuffer) {
  13118. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13119. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13120. var attachments = textures[0]._attachments;
  13121. if (!attachments) {
  13122. attachments = new Array(textures.length);
  13123. textures[0]._attachments = attachments;
  13124. }
  13125. for (var i = 0; i < textures.length; i++) {
  13126. var texture = textures[i];
  13127. for (var j = 0; j < attachments.length; j++) {
  13128. attachments[j] = gl.NONE;
  13129. }
  13130. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13131. gl.readBuffer(attachments[i]);
  13132. gl.drawBuffers(attachments);
  13133. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13134. }
  13135. for (var i = 0; i < attachments.length; i++) {
  13136. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13137. }
  13138. gl.drawBuffers(attachments);
  13139. }
  13140. for (var i = 0; i < textures.length; i++) {
  13141. var texture = textures[i];
  13142. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13143. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13144. gl.generateMipmap(gl.TEXTURE_2D);
  13145. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13146. }
  13147. }
  13148. if (onBeforeUnbind) {
  13149. if (textures[0]._MSAAFramebuffer) {
  13150. // Bind the correct framebuffer
  13151. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13152. }
  13153. onBeforeUnbind();
  13154. }
  13155. this.bindUnboundFramebuffer(null);
  13156. };
  13157. /**
  13158. * Force the mipmap generation for the given render target texture
  13159. * @param texture defines the render target texture to use
  13160. */
  13161. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13162. if (texture.generateMipMaps) {
  13163. var gl = this._gl;
  13164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13165. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13167. }
  13168. };
  13169. /**
  13170. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13171. */
  13172. Engine.prototype.flushFramebuffer = function () {
  13173. this._gl.flush();
  13174. };
  13175. /**
  13176. * Unbind the current render target and bind the default framebuffer
  13177. */
  13178. Engine.prototype.restoreDefaultFramebuffer = function () {
  13179. if (this._currentRenderTarget) {
  13180. this.unBindFramebuffer(this._currentRenderTarget);
  13181. }
  13182. else {
  13183. this.bindUnboundFramebuffer(null);
  13184. }
  13185. if (this._cachedViewport) {
  13186. this.setViewport(this._cachedViewport);
  13187. }
  13188. this.wipeCaches();
  13189. };
  13190. // UBOs
  13191. /**
  13192. * Create an uniform buffer
  13193. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13194. * @param elements defines the content of the uniform buffer
  13195. * @returns the webGL uniform buffer
  13196. */
  13197. Engine.prototype.createUniformBuffer = function (elements) {
  13198. var ubo = this._gl.createBuffer();
  13199. if (!ubo) {
  13200. throw new Error("Unable to create uniform buffer");
  13201. }
  13202. this.bindUniformBuffer(ubo);
  13203. if (elements instanceof Float32Array) {
  13204. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13205. }
  13206. else {
  13207. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13208. }
  13209. this.bindUniformBuffer(null);
  13210. ubo.references = 1;
  13211. return ubo;
  13212. };
  13213. /**
  13214. * Create a dynamic uniform buffer
  13215. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13216. * @param elements defines the content of the uniform buffer
  13217. * @returns the webGL uniform buffer
  13218. */
  13219. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13220. var ubo = this._gl.createBuffer();
  13221. if (!ubo) {
  13222. throw new Error("Unable to create dynamic uniform buffer");
  13223. }
  13224. this.bindUniformBuffer(ubo);
  13225. if (elements instanceof Float32Array) {
  13226. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13227. }
  13228. else {
  13229. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13230. }
  13231. this.bindUniformBuffer(null);
  13232. ubo.references = 1;
  13233. return ubo;
  13234. };
  13235. /**
  13236. * Update an existing uniform buffer
  13237. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13238. * @param uniformBuffer defines the target uniform buffer
  13239. * @param elements defines the content to update
  13240. * @param offset defines the offset in the uniform buffer where update should start
  13241. * @param count defines the size of the data to update
  13242. */
  13243. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13244. this.bindUniformBuffer(uniformBuffer);
  13245. if (offset === undefined) {
  13246. offset = 0;
  13247. }
  13248. if (count === undefined) {
  13249. if (elements instanceof Float32Array) {
  13250. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13251. }
  13252. else {
  13253. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13254. }
  13255. }
  13256. else {
  13257. if (elements instanceof Float32Array) {
  13258. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13259. }
  13260. else {
  13261. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13262. }
  13263. }
  13264. this.bindUniformBuffer(null);
  13265. };
  13266. // VBOs
  13267. Engine.prototype._resetVertexBufferBinding = function () {
  13268. this.bindArrayBuffer(null);
  13269. this._cachedVertexBuffers = null;
  13270. };
  13271. /**
  13272. * Creates a vertex buffer
  13273. * @param data the data for the vertex buffer
  13274. * @returns the new WebGL static buffer
  13275. */
  13276. Engine.prototype.createVertexBuffer = function (data) {
  13277. var vbo = this._gl.createBuffer();
  13278. if (!vbo) {
  13279. throw new Error("Unable to create vertex buffer");
  13280. }
  13281. this.bindArrayBuffer(vbo);
  13282. if (data instanceof Array) {
  13283. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13284. }
  13285. else {
  13286. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13287. }
  13288. this._resetVertexBufferBinding();
  13289. vbo.references = 1;
  13290. return vbo;
  13291. };
  13292. /**
  13293. * Creates a dynamic vertex buffer
  13294. * @param data the data for the dynamic vertex buffer
  13295. * @returns the new WebGL dynamic buffer
  13296. */
  13297. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13298. var vbo = this._gl.createBuffer();
  13299. if (!vbo) {
  13300. throw new Error("Unable to create dynamic vertex buffer");
  13301. }
  13302. this.bindArrayBuffer(vbo);
  13303. if (data instanceof Array) {
  13304. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13305. }
  13306. else {
  13307. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13308. }
  13309. this._resetVertexBufferBinding();
  13310. vbo.references = 1;
  13311. return vbo;
  13312. };
  13313. /**
  13314. * Update a dynamic index buffer
  13315. * @param indexBuffer defines the target index buffer
  13316. * @param indices defines the data to update
  13317. * @param offset defines the offset in the target index buffer where update should start
  13318. */
  13319. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13320. if (offset === void 0) { offset = 0; }
  13321. // Force cache update
  13322. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13323. this.bindIndexBuffer(indexBuffer);
  13324. var arrayBuffer;
  13325. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13326. arrayBuffer = indices;
  13327. }
  13328. else {
  13329. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13330. }
  13331. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13332. this._resetIndexBufferBinding();
  13333. };
  13334. /**
  13335. * Updates a dynamic vertex buffer.
  13336. * @param vertexBuffer the vertex buffer to update
  13337. * @param data the data used to update the vertex buffer
  13338. * @param byteOffset the byte offset of the data
  13339. * @param byteLength the byte length of the data
  13340. */
  13341. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13342. this.bindArrayBuffer(vertexBuffer);
  13343. if (byteOffset === undefined) {
  13344. byteOffset = 0;
  13345. }
  13346. if (byteLength === undefined) {
  13347. if (data instanceof Array) {
  13348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13349. }
  13350. else {
  13351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13352. }
  13353. }
  13354. else {
  13355. if (data instanceof Array) {
  13356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13357. }
  13358. else {
  13359. if (data instanceof ArrayBuffer) {
  13360. data = new Uint8Array(data, byteOffset, byteLength);
  13361. }
  13362. else {
  13363. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13364. }
  13365. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13366. }
  13367. }
  13368. this._resetVertexBufferBinding();
  13369. };
  13370. Engine.prototype._resetIndexBufferBinding = function () {
  13371. this.bindIndexBuffer(null);
  13372. this._cachedIndexBuffer = null;
  13373. };
  13374. /**
  13375. * Creates a new index buffer
  13376. * @param indices defines the content of the index buffer
  13377. * @param updatable defines if the index buffer must be updatable
  13378. * @returns a new webGL buffer
  13379. */
  13380. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13381. var vbo = this._gl.createBuffer();
  13382. if (!vbo) {
  13383. throw new Error("Unable to create index buffer");
  13384. }
  13385. this.bindIndexBuffer(vbo);
  13386. // Check for 32 bits indices
  13387. var arrayBuffer;
  13388. var need32Bits = false;
  13389. if (indices instanceof Uint16Array) {
  13390. arrayBuffer = indices;
  13391. }
  13392. else {
  13393. //check 32 bit support
  13394. if (this._caps.uintIndices) {
  13395. if (indices instanceof Uint32Array) {
  13396. arrayBuffer = indices;
  13397. need32Bits = true;
  13398. }
  13399. else {
  13400. //number[] or Int32Array, check if 32 bit is necessary
  13401. for (var index = 0; index < indices.length; index++) {
  13402. if (indices[index] > 65535) {
  13403. need32Bits = true;
  13404. break;
  13405. }
  13406. }
  13407. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13408. }
  13409. }
  13410. else {
  13411. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13412. arrayBuffer = new Uint16Array(indices);
  13413. }
  13414. }
  13415. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13416. this._resetIndexBufferBinding();
  13417. vbo.references = 1;
  13418. vbo.is32Bits = need32Bits;
  13419. return vbo;
  13420. };
  13421. /**
  13422. * Bind a webGL buffer to the webGL context
  13423. * @param buffer defines the buffer to bind
  13424. */
  13425. Engine.prototype.bindArrayBuffer = function (buffer) {
  13426. if (!this._vaoRecordInProgress) {
  13427. this._unbindVertexArrayObject();
  13428. }
  13429. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13430. };
  13431. /**
  13432. * Bind an uniform buffer to the current webGL context
  13433. * @param buffer defines the buffer to bind
  13434. */
  13435. Engine.prototype.bindUniformBuffer = function (buffer) {
  13436. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13437. };
  13438. /**
  13439. * Bind a buffer to the current webGL context at a given location
  13440. * @param buffer defines the buffer to bind
  13441. * @param location defines the index where to bind the buffer
  13442. */
  13443. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13444. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13445. };
  13446. /**
  13447. * Bind a specific block at a given index in a specific shader program
  13448. * @param shaderProgram defines the shader program
  13449. * @param blockName defines the block name
  13450. * @param index defines the index where to bind the block
  13451. */
  13452. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13453. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13454. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13455. };
  13456. ;
  13457. Engine.prototype.bindIndexBuffer = function (buffer) {
  13458. if (!this._vaoRecordInProgress) {
  13459. this._unbindVertexArrayObject();
  13460. }
  13461. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13462. };
  13463. Engine.prototype.bindBuffer = function (buffer, target) {
  13464. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13465. this._gl.bindBuffer(target, buffer);
  13466. this._currentBoundBuffer[target] = buffer;
  13467. }
  13468. };
  13469. /**
  13470. * update the bound buffer with the given data
  13471. * @param data defines the data to update
  13472. */
  13473. Engine.prototype.updateArrayBuffer = function (data) {
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13475. };
  13476. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13477. var pointer = this._currentBufferPointers[indx];
  13478. var changed = false;
  13479. if (!pointer.active) {
  13480. changed = true;
  13481. pointer.active = true;
  13482. pointer.index = indx;
  13483. pointer.size = size;
  13484. pointer.type = type;
  13485. pointer.normalized = normalized;
  13486. pointer.stride = stride;
  13487. pointer.offset = offset;
  13488. pointer.buffer = buffer;
  13489. }
  13490. else {
  13491. if (pointer.buffer !== buffer) {
  13492. pointer.buffer = buffer;
  13493. changed = true;
  13494. }
  13495. if (pointer.size !== size) {
  13496. pointer.size = size;
  13497. changed = true;
  13498. }
  13499. if (pointer.type !== type) {
  13500. pointer.type = type;
  13501. changed = true;
  13502. }
  13503. if (pointer.normalized !== normalized) {
  13504. pointer.normalized = normalized;
  13505. changed = true;
  13506. }
  13507. if (pointer.stride !== stride) {
  13508. pointer.stride = stride;
  13509. changed = true;
  13510. }
  13511. if (pointer.offset !== offset) {
  13512. pointer.offset = offset;
  13513. changed = true;
  13514. }
  13515. }
  13516. if (changed || this._vaoRecordInProgress) {
  13517. this.bindArrayBuffer(buffer);
  13518. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13519. }
  13520. };
  13521. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13522. if (indexBuffer == null) {
  13523. return;
  13524. }
  13525. if (this._cachedIndexBuffer !== indexBuffer) {
  13526. this._cachedIndexBuffer = indexBuffer;
  13527. this.bindIndexBuffer(indexBuffer);
  13528. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13529. }
  13530. };
  13531. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13532. var attributes = effect.getAttributesNames();
  13533. if (!this._vaoRecordInProgress) {
  13534. this._unbindVertexArrayObject();
  13535. }
  13536. this.unbindAllAttributes();
  13537. for (var index = 0; index < attributes.length; index++) {
  13538. var order = effect.getAttributeLocation(index);
  13539. if (order >= 0) {
  13540. var vertexBuffer = vertexBuffers[attributes[index]];
  13541. if (!vertexBuffer) {
  13542. continue;
  13543. }
  13544. this._gl.enableVertexAttribArray(order);
  13545. if (!this._vaoRecordInProgress) {
  13546. this._vertexAttribArraysEnabled[order] = true;
  13547. }
  13548. var buffer = vertexBuffer.getBuffer();
  13549. if (buffer) {
  13550. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13551. if (vertexBuffer.getIsInstanced()) {
  13552. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13553. if (!this._vaoRecordInProgress) {
  13554. this._currentInstanceLocations.push(order);
  13555. this._currentInstanceBuffers.push(buffer);
  13556. }
  13557. }
  13558. }
  13559. }
  13560. }
  13561. };
  13562. /**
  13563. * Records a vertex array object
  13564. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13565. * @param vertexBuffers defines the list of vertex buffers to store
  13566. * @param indexBuffer defines the index buffer to store
  13567. * @param effect defines the effect to store
  13568. * @returns the new vertex array object
  13569. */
  13570. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13571. var vao = this._gl.createVertexArray();
  13572. this._vaoRecordInProgress = true;
  13573. this._gl.bindVertexArray(vao);
  13574. this._mustWipeVertexAttributes = true;
  13575. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13576. this.bindIndexBuffer(indexBuffer);
  13577. this._vaoRecordInProgress = false;
  13578. this._gl.bindVertexArray(null);
  13579. return vao;
  13580. };
  13581. /**
  13582. * Bind a specific vertex array object
  13583. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13584. * @param vertexArrayObject defines the vertex array object to bind
  13585. * @param indexBuffer defines the index buffer to bind
  13586. */
  13587. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13588. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13589. this._cachedVertexArrayObject = vertexArrayObject;
  13590. this._gl.bindVertexArray(vertexArrayObject);
  13591. this._cachedVertexBuffers = null;
  13592. this._cachedIndexBuffer = null;
  13593. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13594. this._mustWipeVertexAttributes = true;
  13595. }
  13596. };
  13597. /**
  13598. * Bind webGl buffers directly to the webGL context
  13599. * @param vertexBuffer defines the vertex buffer to bind
  13600. * @param indexBuffer defines the index buffer to bind
  13601. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13602. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13603. * @param effect defines the effect associated with the vertex buffer
  13604. */
  13605. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13606. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13607. this._cachedVertexBuffers = vertexBuffer;
  13608. this._cachedEffectForVertexBuffers = effect;
  13609. var attributesCount = effect.getAttributesCount();
  13610. this._unbindVertexArrayObject();
  13611. this.unbindAllAttributes();
  13612. var offset = 0;
  13613. for (var index = 0; index < attributesCount; index++) {
  13614. if (index < vertexDeclaration.length) {
  13615. var order = effect.getAttributeLocation(index);
  13616. if (order >= 0) {
  13617. this._gl.enableVertexAttribArray(order);
  13618. this._vertexAttribArraysEnabled[order] = true;
  13619. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13620. }
  13621. offset += vertexDeclaration[index] * 4;
  13622. }
  13623. }
  13624. }
  13625. this._bindIndexBufferWithCache(indexBuffer);
  13626. };
  13627. Engine.prototype._unbindVertexArrayObject = function () {
  13628. if (!this._cachedVertexArrayObject) {
  13629. return;
  13630. }
  13631. this._cachedVertexArrayObject = null;
  13632. this._gl.bindVertexArray(null);
  13633. };
  13634. /**
  13635. * Bind a list of vertex buffers to the webGL context
  13636. * @param vertexBuffers defines the list of vertex buffers to bind
  13637. * @param indexBuffer defines the index buffer to bind
  13638. * @param effect defines the effect associated with the vertex buffers
  13639. */
  13640. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13641. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13642. this._cachedVertexBuffers = vertexBuffers;
  13643. this._cachedEffectForVertexBuffers = effect;
  13644. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13645. }
  13646. this._bindIndexBufferWithCache(indexBuffer);
  13647. };
  13648. /**
  13649. * Unbind all instance attributes
  13650. */
  13651. Engine.prototype.unbindInstanceAttributes = function () {
  13652. var boundBuffer;
  13653. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13654. var instancesBuffer = this._currentInstanceBuffers[i];
  13655. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13656. boundBuffer = instancesBuffer;
  13657. this.bindArrayBuffer(instancesBuffer);
  13658. }
  13659. var offsetLocation = this._currentInstanceLocations[i];
  13660. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13661. }
  13662. this._currentInstanceBuffers.length = 0;
  13663. this._currentInstanceLocations.length = 0;
  13664. };
  13665. /**
  13666. * Release and free the memory of a vertex array object
  13667. * @param vao defines the vertex array object to delete
  13668. */
  13669. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13670. this._gl.deleteVertexArray(vao);
  13671. };
  13672. /** @hidden */
  13673. Engine.prototype._releaseBuffer = function (buffer) {
  13674. buffer.references--;
  13675. if (buffer.references === 0) {
  13676. this._gl.deleteBuffer(buffer);
  13677. return true;
  13678. }
  13679. return false;
  13680. };
  13681. /**
  13682. * Creates a webGL buffer to use with instanciation
  13683. * @param capacity defines the size of the buffer
  13684. * @returns the webGL buffer
  13685. */
  13686. Engine.prototype.createInstancesBuffer = function (capacity) {
  13687. var buffer = this._gl.createBuffer();
  13688. if (!buffer) {
  13689. throw new Error("Unable to create instance buffer");
  13690. }
  13691. buffer.capacity = capacity;
  13692. this.bindArrayBuffer(buffer);
  13693. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13694. return buffer;
  13695. };
  13696. /**
  13697. * Delete a webGL buffer used with instanciation
  13698. * @param buffer defines the webGL buffer to delete
  13699. */
  13700. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13701. this._gl.deleteBuffer(buffer);
  13702. };
  13703. /**
  13704. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13705. * @param instancesBuffer defines the webGL buffer to update and bind
  13706. * @param data defines the data to store in the buffer
  13707. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13708. */
  13709. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13710. this.bindArrayBuffer(instancesBuffer);
  13711. if (data) {
  13712. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13713. }
  13714. if (offsetLocations[0].index !== undefined) {
  13715. var stride = 0;
  13716. for (var i = 0; i < offsetLocations.length; i++) {
  13717. var ai = offsetLocations[i];
  13718. stride += ai.attributeSize * 4;
  13719. }
  13720. for (var i = 0; i < offsetLocations.length; i++) {
  13721. var ai = offsetLocations[i];
  13722. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13723. this._gl.enableVertexAttribArray(ai.index);
  13724. this._vertexAttribArraysEnabled[ai.index] = true;
  13725. }
  13726. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13727. this._gl.vertexAttribDivisor(ai.index, 1);
  13728. this._currentInstanceLocations.push(ai.index);
  13729. this._currentInstanceBuffers.push(instancesBuffer);
  13730. }
  13731. }
  13732. else {
  13733. for (var index = 0; index < 4; index++) {
  13734. var offsetLocation = offsetLocations[index];
  13735. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13736. this._gl.enableVertexAttribArray(offsetLocation);
  13737. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13738. }
  13739. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13740. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13741. this._currentInstanceLocations.push(offsetLocation);
  13742. this._currentInstanceBuffers.push(instancesBuffer);
  13743. }
  13744. }
  13745. };
  13746. /**
  13747. * Apply all cached states (depth, culling, stencil and alpha)
  13748. */
  13749. Engine.prototype.applyStates = function () {
  13750. this._depthCullingState.apply(this._gl);
  13751. this._stencilState.apply(this._gl);
  13752. this._alphaState.apply(this._gl);
  13753. };
  13754. /**
  13755. * Send a draw order
  13756. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13757. * @param indexStart defines the starting index
  13758. * @param indexCount defines the number of index to draw
  13759. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13760. */
  13761. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13762. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13763. };
  13764. /**
  13765. * Draw a list of points
  13766. * @param verticesStart defines the index of first vertex to draw
  13767. * @param verticesCount defines the count of vertices to draw
  13768. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13769. */
  13770. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13771. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13772. };
  13773. /**
  13774. * Draw a list of unindexed primitives
  13775. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13776. * @param verticesStart defines the index of first vertex to draw
  13777. * @param verticesCount defines the count of vertices to draw
  13778. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13779. */
  13780. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13781. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13782. };
  13783. /**
  13784. * Draw a list of indexed primitives
  13785. * @param fillMode defines the primitive to use
  13786. * @param indexStart defines the starting index
  13787. * @param indexCount defines the number of index to draw
  13788. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13789. */
  13790. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13791. // Apply states
  13792. this.applyStates();
  13793. this._drawCalls.addCount(1, false);
  13794. // Render
  13795. var drawMode = this._drawMode(fillMode);
  13796. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13797. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13798. if (instancesCount) {
  13799. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13800. }
  13801. else {
  13802. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13803. }
  13804. };
  13805. /**
  13806. * Draw a list of unindexed primitives
  13807. * @param fillMode defines the primitive to use
  13808. * @param verticesStart defines the index of first vertex to draw
  13809. * @param verticesCount defines the count of vertices to draw
  13810. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13811. */
  13812. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13813. // Apply states
  13814. this.applyStates();
  13815. this._drawCalls.addCount(1, false);
  13816. var drawMode = this._drawMode(fillMode);
  13817. if (instancesCount) {
  13818. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13819. }
  13820. else {
  13821. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13822. }
  13823. };
  13824. Engine.prototype._drawMode = function (fillMode) {
  13825. switch (fillMode) {
  13826. // Triangle views
  13827. case BABYLON.Material.TriangleFillMode:
  13828. return this._gl.TRIANGLES;
  13829. case BABYLON.Material.PointFillMode:
  13830. return this._gl.POINTS;
  13831. case BABYLON.Material.WireFrameFillMode:
  13832. return this._gl.LINES;
  13833. // Draw modes
  13834. case BABYLON.Material.PointListDrawMode:
  13835. return this._gl.POINTS;
  13836. case BABYLON.Material.LineListDrawMode:
  13837. return this._gl.LINES;
  13838. case BABYLON.Material.LineLoopDrawMode:
  13839. return this._gl.LINE_LOOP;
  13840. case BABYLON.Material.LineStripDrawMode:
  13841. return this._gl.LINE_STRIP;
  13842. case BABYLON.Material.TriangleStripDrawMode:
  13843. return this._gl.TRIANGLE_STRIP;
  13844. case BABYLON.Material.TriangleFanDrawMode:
  13845. return this._gl.TRIANGLE_FAN;
  13846. default:
  13847. return this._gl.TRIANGLES;
  13848. }
  13849. };
  13850. // Shaders
  13851. /** @hidden */
  13852. Engine.prototype._releaseEffect = function (effect) {
  13853. if (this._compiledEffects[effect._key]) {
  13854. delete this._compiledEffects[effect._key];
  13855. this._deleteProgram(effect.getProgram());
  13856. }
  13857. };
  13858. /** @hidden */
  13859. Engine.prototype._deleteProgram = function (program) {
  13860. if (program) {
  13861. program.__SPECTOR_rebuildProgram = null;
  13862. if (program.transformFeedback) {
  13863. this.deleteTransformFeedback(program.transformFeedback);
  13864. program.transformFeedback = null;
  13865. }
  13866. this._gl.deleteProgram(program);
  13867. }
  13868. };
  13869. /**
  13870. * Create a new effect (used to store vertex/fragment shaders)
  13871. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13872. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13873. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13874. * @param samplers defines an array of string used to represent textures
  13875. * @param defines defines the string containing the defines to use to compile the shaders
  13876. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13877. * @param onCompiled defines a function to call when the effect creation is successful
  13878. * @param onError defines a function to call when the effect creation has failed
  13879. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13880. * @returns the new Effect
  13881. */
  13882. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13883. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13884. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13885. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13886. if (this._compiledEffects[name]) {
  13887. var compiledEffect = this._compiledEffects[name];
  13888. if (onCompiled && compiledEffect.isReady()) {
  13889. onCompiled(compiledEffect);
  13890. }
  13891. return compiledEffect;
  13892. }
  13893. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13894. effect._key = name;
  13895. this._compiledEffects[name] = effect;
  13896. return effect;
  13897. };
  13898. /**
  13899. * Create an effect to use with particle systems
  13900. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13901. * @param uniformsNames defines a list of attribute names
  13902. * @param samplers defines an array of string used to represent textures
  13903. * @param defines defines the string containing the defines to use to compile the shaders
  13904. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13905. * @param onCompiled defines a function to call when the effect creation is successful
  13906. * @param onError defines a function to call when the effect creation has failed
  13907. * @returns the new Effect
  13908. */
  13909. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13910. if (uniformsNames === void 0) { uniformsNames = []; }
  13911. if (samplers === void 0) { samplers = []; }
  13912. if (defines === void 0) { defines = ""; }
  13913. return this.createEffect({
  13914. vertex: "particles",
  13915. fragmentElement: fragmentName
  13916. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13917. };
  13918. /**
  13919. * Directly creates a webGL program
  13920. * @param vertexCode defines the vertex shader code to use
  13921. * @param fragmentCode defines the fragment shader code to use
  13922. * @param context defines the webGL context to use (if not set, the current one will be used)
  13923. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13924. * @returns the new webGL program
  13925. */
  13926. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13927. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13928. context = context || this._gl;
  13929. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13930. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13931. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13932. };
  13933. /**
  13934. * Creates a webGL program
  13935. * @param vertexCode defines the vertex shader code to use
  13936. * @param fragmentCode defines the fragment shader code to use
  13937. * @param defines defines the string containing the defines to use to compile the shaders
  13938. * @param context defines the webGL context to use (if not set, the current one will be used)
  13939. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13940. * @returns the new webGL program
  13941. */
  13942. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13943. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13944. context = context || this._gl;
  13945. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13946. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13947. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13948. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13949. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13950. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13951. return program;
  13952. };
  13953. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13954. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13955. var shaderProgram = context.createProgram();
  13956. if (!shaderProgram) {
  13957. throw new Error("Unable to create program");
  13958. }
  13959. context.attachShader(shaderProgram, vertexShader);
  13960. context.attachShader(shaderProgram, fragmentShader);
  13961. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13962. var transformFeedback = this.createTransformFeedback();
  13963. this.bindTransformFeedback(transformFeedback);
  13964. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13965. shaderProgram.transformFeedback = transformFeedback;
  13966. }
  13967. context.linkProgram(shaderProgram);
  13968. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13969. this.bindTransformFeedback(null);
  13970. }
  13971. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13972. if (!linked) {
  13973. context.validateProgram(shaderProgram);
  13974. var error = context.getProgramInfoLog(shaderProgram);
  13975. if (error) {
  13976. throw new Error(error);
  13977. }
  13978. }
  13979. context.deleteShader(vertexShader);
  13980. context.deleteShader(fragmentShader);
  13981. return shaderProgram;
  13982. };
  13983. /**
  13984. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13985. * @param shaderProgram defines the webGL program to use
  13986. * @param uniformsNames defines the list of uniform names
  13987. * @returns an array of webGL uniform locations
  13988. */
  13989. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13990. var results = new Array();
  13991. for (var index = 0; index < uniformsNames.length; index++) {
  13992. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13993. }
  13994. return results;
  13995. };
  13996. /**
  13997. * Gets the lsit of active attributes for a given webGL program
  13998. * @param shaderProgram defines the webGL program to use
  13999. * @param attributesNames defines the list of attribute names to get
  14000. * @returns an array of indices indicating the offset of each attribute
  14001. */
  14002. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14003. var results = [];
  14004. for (var index = 0; index < attributesNames.length; index++) {
  14005. try {
  14006. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14007. }
  14008. catch (e) {
  14009. results.push(-1);
  14010. }
  14011. }
  14012. return results;
  14013. };
  14014. /**
  14015. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14016. * @param effect defines the effect to activate
  14017. */
  14018. Engine.prototype.enableEffect = function (effect) {
  14019. if (!effect) {
  14020. return;
  14021. }
  14022. // Use program
  14023. this.bindSamplers(effect);
  14024. this._currentEffect = effect;
  14025. if (effect.onBind) {
  14026. effect.onBind(effect);
  14027. }
  14028. effect.onBindObservable.notifyObservers(effect);
  14029. };
  14030. /**
  14031. * Set the value of an uniform to an array of int32
  14032. * @param uniform defines the webGL uniform location where to store the value
  14033. * @param array defines the array of int32 to store
  14034. */
  14035. Engine.prototype.setIntArray = function (uniform, array) {
  14036. if (!uniform)
  14037. return;
  14038. this._gl.uniform1iv(uniform, array);
  14039. };
  14040. /**
  14041. * Set the value of an uniform to an array of int32 (stored as vec2)
  14042. * @param uniform defines the webGL uniform location where to store the value
  14043. * @param array defines the array of int32 to store
  14044. */
  14045. Engine.prototype.setIntArray2 = function (uniform, array) {
  14046. if (!uniform || array.length % 2 !== 0)
  14047. return;
  14048. this._gl.uniform2iv(uniform, array);
  14049. };
  14050. /**
  14051. * Set the value of an uniform to an array of int32 (stored as vec3)
  14052. * @param uniform defines the webGL uniform location where to store the value
  14053. * @param array defines the array of int32 to store
  14054. */
  14055. Engine.prototype.setIntArray3 = function (uniform, array) {
  14056. if (!uniform || array.length % 3 !== 0)
  14057. return;
  14058. this._gl.uniform3iv(uniform, array);
  14059. };
  14060. /**
  14061. * Set the value of an uniform to an array of int32 (stored as vec4)
  14062. * @param uniform defines the webGL uniform location where to store the value
  14063. * @param array defines the array of int32 to store
  14064. */
  14065. Engine.prototype.setIntArray4 = function (uniform, array) {
  14066. if (!uniform || array.length % 4 !== 0)
  14067. return;
  14068. this._gl.uniform4iv(uniform, array);
  14069. };
  14070. /**
  14071. * Set the value of an uniform to an array of float32
  14072. * @param uniform defines the webGL uniform location where to store the value
  14073. * @param array defines the array of float32 to store
  14074. */
  14075. Engine.prototype.setFloatArray = function (uniform, array) {
  14076. if (!uniform)
  14077. return;
  14078. this._gl.uniform1fv(uniform, array);
  14079. };
  14080. /**
  14081. * Set the value of an uniform to an array of float32 (stored as vec2)
  14082. * @param uniform defines the webGL uniform location where to store the value
  14083. * @param array defines the array of float32 to store
  14084. */
  14085. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14086. if (!uniform || array.length % 2 !== 0)
  14087. return;
  14088. this._gl.uniform2fv(uniform, array);
  14089. };
  14090. /**
  14091. * Set the value of an uniform to an array of float32 (stored as vec3)
  14092. * @param uniform defines the webGL uniform location where to store the value
  14093. * @param array defines the array of float32 to store
  14094. */
  14095. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14096. if (!uniform || array.length % 3 !== 0)
  14097. return;
  14098. this._gl.uniform3fv(uniform, array);
  14099. };
  14100. /**
  14101. * Set the value of an uniform to an array of float32 (stored as vec4)
  14102. * @param uniform defines the webGL uniform location where to store the value
  14103. * @param array defines the array of float32 to store
  14104. */
  14105. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14106. if (!uniform || array.length % 4 !== 0)
  14107. return;
  14108. this._gl.uniform4fv(uniform, array);
  14109. };
  14110. /**
  14111. * Set the value of an uniform to an array of number
  14112. * @param uniform defines the webGL uniform location where to store the value
  14113. * @param array defines the array of number to store
  14114. */
  14115. Engine.prototype.setArray = function (uniform, array) {
  14116. if (!uniform)
  14117. return;
  14118. this._gl.uniform1fv(uniform, array);
  14119. };
  14120. /**
  14121. * Set the value of an uniform to an array of number (stored as vec2)
  14122. * @param uniform defines the webGL uniform location where to store the value
  14123. * @param array defines the array of number to store
  14124. */
  14125. Engine.prototype.setArray2 = function (uniform, array) {
  14126. if (!uniform || array.length % 2 !== 0)
  14127. return;
  14128. this._gl.uniform2fv(uniform, array);
  14129. };
  14130. /**
  14131. * Set the value of an uniform to an array of number (stored as vec3)
  14132. * @param uniform defines the webGL uniform location where to store the value
  14133. * @param array defines the array of number to store
  14134. */
  14135. Engine.prototype.setArray3 = function (uniform, array) {
  14136. if (!uniform || array.length % 3 !== 0)
  14137. return;
  14138. this._gl.uniform3fv(uniform, array);
  14139. };
  14140. /**
  14141. * Set the value of an uniform to an array of number (stored as vec4)
  14142. * @param uniform defines the webGL uniform location where to store the value
  14143. * @param array defines the array of number to store
  14144. */
  14145. Engine.prototype.setArray4 = function (uniform, array) {
  14146. if (!uniform || array.length % 4 !== 0)
  14147. return;
  14148. this._gl.uniform4fv(uniform, array);
  14149. };
  14150. /**
  14151. * Set the value of an uniform to an array of float32 (stored as matrices)
  14152. * @param uniform defines the webGL uniform location where to store the value
  14153. * @param matrices defines the array of float32 to store
  14154. */
  14155. Engine.prototype.setMatrices = function (uniform, matrices) {
  14156. if (!uniform)
  14157. return;
  14158. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14159. };
  14160. /**
  14161. * Set the value of an uniform to a matrix
  14162. * @param uniform defines the webGL uniform location where to store the value
  14163. * @param matrix defines the matrix to store
  14164. */
  14165. Engine.prototype.setMatrix = function (uniform, matrix) {
  14166. if (!uniform)
  14167. return;
  14168. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14169. };
  14170. /**
  14171. * Set the value of an uniform to a matrix (3x3)
  14172. * @param uniform defines the webGL uniform location where to store the value
  14173. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14174. */
  14175. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14176. if (!uniform)
  14177. return;
  14178. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14179. };
  14180. /**
  14181. * Set the value of an uniform to a matrix (2x2)
  14182. * @param uniform defines the webGL uniform location where to store the value
  14183. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14184. */
  14185. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14186. if (!uniform)
  14187. return;
  14188. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14189. };
  14190. /**
  14191. * Set the value of an uniform to a number (int)
  14192. * @param uniform defines the webGL uniform location where to store the value
  14193. * @param value defines the int number to store
  14194. */
  14195. Engine.prototype.setInt = function (uniform, value) {
  14196. if (!uniform)
  14197. return;
  14198. this._gl.uniform1i(uniform, value);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to a number (float)
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param value defines the float number to store
  14204. */
  14205. Engine.prototype.setFloat = function (uniform, value) {
  14206. if (!uniform)
  14207. return;
  14208. this._gl.uniform1f(uniform, value);
  14209. };
  14210. /**
  14211. * Set the value of an uniform to a vec2
  14212. * @param uniform defines the webGL uniform location where to store the value
  14213. * @param x defines the 1st component of the value
  14214. * @param y defines the 2nd component of the value
  14215. */
  14216. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14217. if (!uniform)
  14218. return;
  14219. this._gl.uniform2f(uniform, x, y);
  14220. };
  14221. /**
  14222. * Set the value of an uniform to a vec3
  14223. * @param uniform defines the webGL uniform location where to store the value
  14224. * @param x defines the 1st component of the value
  14225. * @param y defines the 2nd component of the value
  14226. * @param z defines the 3rd component of the value
  14227. */
  14228. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14229. if (!uniform)
  14230. return;
  14231. this._gl.uniform3f(uniform, x, y, z);
  14232. };
  14233. /**
  14234. * Set the value of an uniform to a boolean
  14235. * @param uniform defines the webGL uniform location where to store the value
  14236. * @param bool defines the boolean to store
  14237. */
  14238. Engine.prototype.setBool = function (uniform, bool) {
  14239. if (!uniform)
  14240. return;
  14241. this._gl.uniform1i(uniform, bool);
  14242. };
  14243. /**
  14244. * Set the value of an uniform to a vec4
  14245. * @param uniform defines the webGL uniform location where to store the value
  14246. * @param x defines the 1st component of the value
  14247. * @param y defines the 2nd component of the value
  14248. * @param z defines the 3rd component of the value
  14249. * @param w defines the 4th component of the value
  14250. */
  14251. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14252. if (!uniform)
  14253. return;
  14254. this._gl.uniform4f(uniform, x, y, z, w);
  14255. };
  14256. /**
  14257. * Set the value of an uniform to a Color3
  14258. * @param uniform defines the webGL uniform location where to store the value
  14259. * @param color3 defines the color to store
  14260. */
  14261. Engine.prototype.setColor3 = function (uniform, color3) {
  14262. if (!uniform)
  14263. return;
  14264. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14265. };
  14266. /**
  14267. * Set the value of an uniform to a Color3 and an alpha value
  14268. * @param uniform defines the webGL uniform location where to store the value
  14269. * @param color3 defines the color to store
  14270. * @param alpha defines the alpha component to store
  14271. */
  14272. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14273. if (!uniform)
  14274. return;
  14275. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14276. };
  14277. /**
  14278. * Sets a Color4 on a uniform variable
  14279. * @param uniform defines the uniform location
  14280. * @param color4 defines the value to be set
  14281. */
  14282. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14283. if (!uniform)
  14284. return;
  14285. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14286. };
  14287. // States
  14288. /**
  14289. * Set various states to the webGL context
  14290. * @param culling defines backface culling state
  14291. * @param zOffset defines the value to apply to zOffset (0 by default)
  14292. * @param force defines if states must be applied even if cache is up to date
  14293. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14294. */
  14295. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14296. if (zOffset === void 0) { zOffset = 0; }
  14297. if (reverseSide === void 0) { reverseSide = false; }
  14298. // Culling
  14299. if (this._depthCullingState.cull !== culling || force) {
  14300. this._depthCullingState.cull = culling;
  14301. }
  14302. // Cull face
  14303. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14304. if (this._depthCullingState.cullFace !== cullFace || force) {
  14305. this._depthCullingState.cullFace = cullFace;
  14306. }
  14307. // Z offset
  14308. this.setZOffset(zOffset);
  14309. // Front face
  14310. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14311. if (this._depthCullingState.frontFace !== frontFace || force) {
  14312. this._depthCullingState.frontFace = frontFace;
  14313. }
  14314. };
  14315. /**
  14316. * Set the z offset to apply to current rendering
  14317. * @param value defines the offset to apply
  14318. */
  14319. Engine.prototype.setZOffset = function (value) {
  14320. this._depthCullingState.zOffset = value;
  14321. };
  14322. /**
  14323. * Gets the current value of the zOffset
  14324. * @returns the current zOffset state
  14325. */
  14326. Engine.prototype.getZOffset = function () {
  14327. return this._depthCullingState.zOffset;
  14328. };
  14329. /**
  14330. * Enable or disable depth buffering
  14331. * @param enable defines the state to set
  14332. */
  14333. Engine.prototype.setDepthBuffer = function (enable) {
  14334. this._depthCullingState.depthTest = enable;
  14335. };
  14336. /**
  14337. * Gets a boolean indicating if depth writing is enabled
  14338. * @returns the current depth writing state
  14339. */
  14340. Engine.prototype.getDepthWrite = function () {
  14341. return this._depthCullingState.depthMask;
  14342. };
  14343. /**
  14344. * Enable or disable depth writing
  14345. * @param enable defines the state to set
  14346. */
  14347. Engine.prototype.setDepthWrite = function (enable) {
  14348. this._depthCullingState.depthMask = enable;
  14349. };
  14350. /**
  14351. * Enable or disable color writing
  14352. * @param enable defines the state to set
  14353. */
  14354. Engine.prototype.setColorWrite = function (enable) {
  14355. this._gl.colorMask(enable, enable, enable, enable);
  14356. this._colorWrite = enable;
  14357. };
  14358. /**
  14359. * Gets a boolean indicating if color writing is enabled
  14360. * @returns the current color writing state
  14361. */
  14362. Engine.prototype.getColorWrite = function () {
  14363. return this._colorWrite;
  14364. };
  14365. /**
  14366. * Sets alpha constants used by some alpha blending modes
  14367. * @param r defines the red component
  14368. * @param g defines the green component
  14369. * @param b defines the blue component
  14370. * @param a defines the alpha component
  14371. */
  14372. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14373. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14374. };
  14375. /**
  14376. * Sets the current alpha mode
  14377. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14378. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14379. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14380. */
  14381. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14382. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14383. if (this._alphaMode === mode) {
  14384. return;
  14385. }
  14386. switch (mode) {
  14387. case Engine.ALPHA_DISABLE:
  14388. this._alphaState.alphaBlend = false;
  14389. break;
  14390. case Engine.ALPHA_PREMULTIPLIED:
  14391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14392. this._alphaState.alphaBlend = true;
  14393. break;
  14394. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14396. this._alphaState.alphaBlend = true;
  14397. break;
  14398. case Engine.ALPHA_COMBINE:
  14399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14400. this._alphaState.alphaBlend = true;
  14401. break;
  14402. case Engine.ALPHA_ONEONE:
  14403. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14404. this._alphaState.alphaBlend = true;
  14405. break;
  14406. case Engine.ALPHA_ADD:
  14407. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14408. this._alphaState.alphaBlend = true;
  14409. break;
  14410. case Engine.ALPHA_SUBTRACT:
  14411. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14412. this._alphaState.alphaBlend = true;
  14413. break;
  14414. case Engine.ALPHA_MULTIPLY:
  14415. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14416. this._alphaState.alphaBlend = true;
  14417. break;
  14418. case Engine.ALPHA_MAXIMIZED:
  14419. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14420. this._alphaState.alphaBlend = true;
  14421. break;
  14422. case Engine.ALPHA_INTERPOLATE:
  14423. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14424. this._alphaState.alphaBlend = true;
  14425. break;
  14426. case Engine.ALPHA_SCREENMODE:
  14427. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14428. this._alphaState.alphaBlend = true;
  14429. break;
  14430. }
  14431. if (!noDepthWriteChange) {
  14432. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14433. }
  14434. this._alphaMode = mode;
  14435. };
  14436. /**
  14437. * Gets the current alpha mode
  14438. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14439. * @returns the current alpha mode
  14440. */
  14441. Engine.prototype.getAlphaMode = function () {
  14442. return this._alphaMode;
  14443. };
  14444. // Textures
  14445. /**
  14446. * Force the entire cache to be cleared
  14447. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14448. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14449. */
  14450. Engine.prototype.wipeCaches = function (bruteForce) {
  14451. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14452. return;
  14453. }
  14454. this._currentEffect = null;
  14455. if (bruteForce) {
  14456. this.resetTextureCache();
  14457. this._currentProgram = null;
  14458. this._stencilState.reset();
  14459. this._depthCullingState.reset();
  14460. this.setDepthFunctionToLessOrEqual();
  14461. this._alphaState.reset();
  14462. }
  14463. this._resetVertexBufferBinding();
  14464. this._cachedIndexBuffer = null;
  14465. this._cachedEffectForVertexBuffers = null;
  14466. this._unbindVertexArrayObject();
  14467. this.bindIndexBuffer(null);
  14468. };
  14469. /**
  14470. * Set the compressed texture format to use, based on the formats you have, and the formats
  14471. * supported by the hardware / browser.
  14472. *
  14473. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14474. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14475. * to API arguments needed to compressed textures. This puts the burden on the container
  14476. * generator to house the arcane code for determining these for current & future formats.
  14477. *
  14478. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14479. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14480. *
  14481. * Note: The result of this call is not taken into account when a texture is base64.
  14482. *
  14483. * @param formatsAvailable defines the list of those format families you have created
  14484. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14485. *
  14486. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14487. * @returns The extension selected.
  14488. */
  14489. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14490. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14491. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14492. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14493. return this._textureFormatInUse = this._texturesSupported[i];
  14494. }
  14495. }
  14496. }
  14497. // actively set format to nothing, to allow this to be called more than once
  14498. // and possibly fail the 2nd time
  14499. this._textureFormatInUse = null;
  14500. return null;
  14501. };
  14502. /** @hidden */
  14503. Engine.prototype._createTexture = function () {
  14504. var texture = this._gl.createTexture();
  14505. if (!texture) {
  14506. throw new Error("Unable to create texture");
  14507. }
  14508. return texture;
  14509. };
  14510. /**
  14511. * Usually called from BABYLON.Texture.ts.
  14512. * Passed information to create a WebGLTexture
  14513. * @param urlArg defines a value which contains one of the following:
  14514. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14515. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14516. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14517. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14518. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14519. * @param scene needed for loading to the correct scene
  14520. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14521. * @param onLoad optional callback to be called upon successful completion
  14522. * @param onError optional callback to be called upon failure
  14523. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14524. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14525. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14526. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14527. */
  14528. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14529. var _this = this;
  14530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14531. if (onLoad === void 0) { onLoad = null; }
  14532. if (onError === void 0) { onError = null; }
  14533. if (buffer === void 0) { buffer = null; }
  14534. if (fallback === void 0) { fallback = null; }
  14535. if (format === void 0) { format = null; }
  14536. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14537. var fromData = url.substr(0, 5) === "data:";
  14538. var fromBlob = url.substr(0, 5) === "blob:";
  14539. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14540. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14541. // establish the file extension, if possible
  14542. var lastDot = url.lastIndexOf('.');
  14543. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14544. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14545. var isTGA = (extension.indexOf(".tga") === 0);
  14546. // determine if a ktx file should be substituted
  14547. var isKTX = false;
  14548. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14549. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14550. isKTX = true;
  14551. }
  14552. if (scene) {
  14553. scene._addPendingData(texture);
  14554. }
  14555. texture.url = url;
  14556. texture.generateMipMaps = !noMipmap;
  14557. texture.samplingMode = samplingMode;
  14558. texture.invertY = invertY;
  14559. if (!this._doNotHandleContextLost) {
  14560. // Keep a link to the buffer only if we plan to handle context lost
  14561. texture._buffer = buffer;
  14562. }
  14563. var onLoadObserver = null;
  14564. if (onLoad && !fallback) {
  14565. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14566. }
  14567. if (!fallback)
  14568. this._internalTexturesCache.push(texture);
  14569. var onerror = function (message, exception) {
  14570. if (scene) {
  14571. scene._removePendingData(texture);
  14572. }
  14573. if (onLoadObserver) {
  14574. texture.onLoadedObservable.remove(onLoadObserver);
  14575. }
  14576. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14577. if (isKTX) {
  14578. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14579. }
  14580. else if (BABYLON.Tools.UseFallbackTexture) {
  14581. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14582. }
  14583. if (onError) {
  14584. onError(message || "Unknown error", exception);
  14585. }
  14586. };
  14587. var callback = null;
  14588. // processing for non-image formats
  14589. if (isKTX || isTGA || isDDS) {
  14590. if (isKTX) {
  14591. callback = function (data) {
  14592. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14593. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14594. ktx.uploadLevels(_this._gl, !noMipmap);
  14595. return false;
  14596. }, samplingMode);
  14597. };
  14598. }
  14599. else if (isTGA) {
  14600. callback = function (arrayBuffer) {
  14601. var data = new Uint8Array(arrayBuffer);
  14602. var header = BABYLON.TGATools.GetTGAHeader(data);
  14603. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14604. BABYLON.TGATools.UploadContent(_this._gl, data);
  14605. return false;
  14606. }, samplingMode);
  14607. };
  14608. }
  14609. else if (isDDS) {
  14610. callback = function (data) {
  14611. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14612. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14613. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14614. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14615. return false;
  14616. }, samplingMode);
  14617. };
  14618. }
  14619. if (!buffer) {
  14620. this._loadFile(url, function (data) {
  14621. if (callback) {
  14622. callback(data);
  14623. }
  14624. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14625. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14626. });
  14627. }
  14628. else {
  14629. if (callback) {
  14630. callback(buffer);
  14631. }
  14632. }
  14633. // image format processing
  14634. }
  14635. else {
  14636. var onload = function (img) {
  14637. if (fromBlob && !_this._doNotHandleContextLost) {
  14638. // We need to store the image if we need to rebuild the texture
  14639. // in case of a webgl context lost
  14640. texture._buffer = img;
  14641. }
  14642. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14643. var gl = _this._gl;
  14644. var isPot = (img.width === potWidth && img.height === potHeight);
  14645. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14646. if (isPot) {
  14647. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14648. return false;
  14649. }
  14650. // Using shaders to rescale because canvas.drawImage is lossy
  14651. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14652. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14653. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14656. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14657. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14658. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14659. _this._releaseTexture(source);
  14660. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14661. continuationCallback();
  14662. });
  14663. return true;
  14664. }, samplingMode);
  14665. };
  14666. if (!fromData || isBase64) {
  14667. if (buffer instanceof HTMLImageElement) {
  14668. onload(buffer);
  14669. }
  14670. else {
  14671. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14672. }
  14673. }
  14674. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14675. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14676. }
  14677. else {
  14678. onload(buffer);
  14679. }
  14680. }
  14681. return texture;
  14682. };
  14683. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14684. var _this = this;
  14685. var rtt = this.createRenderTargetTexture({
  14686. width: destination.width,
  14687. height: destination.height,
  14688. }, {
  14689. generateMipMaps: false,
  14690. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14691. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14692. generateDepthBuffer: false,
  14693. generateStencilBuffer: false
  14694. });
  14695. if (!this._rescalePostProcess) {
  14696. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14697. }
  14698. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14699. _this._rescalePostProcess.onApply = function (effect) {
  14700. effect._bindTexture("textureSampler", source);
  14701. };
  14702. var hostingScene = scene;
  14703. if (!hostingScene) {
  14704. hostingScene = _this.scenes[_this.scenes.length - 1];
  14705. }
  14706. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14707. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14708. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14709. _this.unBindFramebuffer(rtt);
  14710. _this._releaseTexture(rtt);
  14711. if (onComplete) {
  14712. onComplete();
  14713. }
  14714. });
  14715. };
  14716. /**
  14717. * Update a raw texture
  14718. * @param texture defines the texture to update
  14719. * @param data defines the data to store in the texture
  14720. * @param format defines the format of the data
  14721. * @param invertY defines if data must be stored with Y axis inverted
  14722. * @param compression defines the compression used (null by default)
  14723. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14724. */
  14725. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14726. if (compression === void 0) { compression = null; }
  14727. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14728. if (!texture) {
  14729. return;
  14730. }
  14731. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14732. var internalFormat = this._getInternalFormat(format);
  14733. var textureType = this._getWebGLTextureType(type);
  14734. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14735. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14736. if (!this._doNotHandleContextLost) {
  14737. texture._bufferView = data;
  14738. texture.format = format;
  14739. texture.type = type;
  14740. texture.invertY = invertY;
  14741. texture._compression = compression;
  14742. }
  14743. if (texture.width % 4 !== 0) {
  14744. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14745. }
  14746. if (compression && data) {
  14747. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14748. }
  14749. else {
  14750. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14751. }
  14752. if (texture.generateMipMaps) {
  14753. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14754. }
  14755. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14756. // this.resetTextureCache();
  14757. texture.isReady = true;
  14758. };
  14759. /**
  14760. * Creates a raw texture
  14761. * @param data defines the data to store in the texture
  14762. * @param width defines the width of the texture
  14763. * @param height defines the height of the texture
  14764. * @param format defines the format of the data
  14765. * @param generateMipMaps defines if the engine should generate the mip levels
  14766. * @param invertY defines if data must be stored with Y axis inverted
  14767. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14768. * @param compression defines the compression used (null by default)
  14769. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14770. * @returns the raw texture inside an InternalTexture
  14771. */
  14772. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14773. if (compression === void 0) { compression = null; }
  14774. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14775. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14776. texture.baseWidth = width;
  14777. texture.baseHeight = height;
  14778. texture.width = width;
  14779. texture.height = height;
  14780. texture.format = format;
  14781. texture.generateMipMaps = generateMipMaps;
  14782. texture.samplingMode = samplingMode;
  14783. texture.invertY = invertY;
  14784. texture._compression = compression;
  14785. texture.type = type;
  14786. if (!this._doNotHandleContextLost) {
  14787. texture._bufferView = data;
  14788. }
  14789. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14791. // Filters
  14792. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14793. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14795. if (generateMipMaps) {
  14796. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14797. }
  14798. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14799. this._internalTexturesCache.push(texture);
  14800. return texture;
  14801. };
  14802. /**
  14803. * Creates a dynamic texture
  14804. * @param width defines the width of the texture
  14805. * @param height defines the height of the texture
  14806. * @param generateMipMaps defines if the engine should generate the mip levels
  14807. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14808. * @returns the dynamic texture inside an InternalTexture
  14809. */
  14810. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14811. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14812. texture.baseWidth = width;
  14813. texture.baseHeight = height;
  14814. if (generateMipMaps) {
  14815. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14816. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14817. }
  14818. // this.resetTextureCache();
  14819. texture.width = width;
  14820. texture.height = height;
  14821. texture.isReady = false;
  14822. texture.generateMipMaps = generateMipMaps;
  14823. texture.samplingMode = samplingMode;
  14824. this.updateTextureSamplingMode(samplingMode, texture);
  14825. this._internalTexturesCache.push(texture);
  14826. return texture;
  14827. };
  14828. /**
  14829. * Update the sampling mode of a given texture
  14830. * @param samplingMode defines the required sampling mode
  14831. * @param texture defines the texture to update
  14832. */
  14833. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14834. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14835. if (texture.isCube) {
  14836. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14837. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14838. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14839. }
  14840. else if (texture.is3D) {
  14841. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14842. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14843. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14844. }
  14845. else {
  14846. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14847. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14848. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14849. }
  14850. texture.samplingMode = samplingMode;
  14851. };
  14852. /**
  14853. * Update the content of a dynamic texture
  14854. * @param texture defines the texture to update
  14855. * @param canvas defines the canvas containing the source
  14856. * @param invertY defines if data must be stored with Y axis inverted
  14857. * @param premulAlpha defines if alpha is stored as premultiplied
  14858. * @param format defines the format of the data
  14859. */
  14860. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14861. if (premulAlpha === void 0) { premulAlpha = false; }
  14862. if (!texture) {
  14863. return;
  14864. }
  14865. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14866. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14867. if (premulAlpha) {
  14868. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14869. }
  14870. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14871. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14872. if (texture.generateMipMaps) {
  14873. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14874. }
  14875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14876. if (premulAlpha) {
  14877. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14878. }
  14879. texture.isReady = true;
  14880. };
  14881. /**
  14882. * Update a video texture
  14883. * @param texture defines the texture to update
  14884. * @param video defines the video element to use
  14885. * @param invertY defines if data must be stored with Y axis inverted
  14886. */
  14887. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14888. if (!texture || texture._isDisabled) {
  14889. return;
  14890. }
  14891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14892. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14893. try {
  14894. // Testing video texture support
  14895. if (this._videoTextureSupported === undefined) {
  14896. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14897. if (this._gl.getError() !== 0) {
  14898. this._videoTextureSupported = false;
  14899. }
  14900. else {
  14901. this._videoTextureSupported = true;
  14902. }
  14903. }
  14904. // Copy video through the current working canvas if video texture is not supported
  14905. if (!this._videoTextureSupported) {
  14906. if (!texture._workingCanvas) {
  14907. texture._workingCanvas = document.createElement("canvas");
  14908. var context = texture._workingCanvas.getContext("2d");
  14909. if (!context) {
  14910. throw new Error("Unable to get 2d context");
  14911. }
  14912. texture._workingContext = context;
  14913. texture._workingCanvas.width = texture.width;
  14914. texture._workingCanvas.height = texture.height;
  14915. }
  14916. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14917. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14918. }
  14919. else {
  14920. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14921. }
  14922. if (texture.generateMipMaps) {
  14923. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14924. }
  14925. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14926. // this.resetTextureCache();
  14927. texture.isReady = true;
  14928. }
  14929. catch (ex) {
  14930. // Something unexpected
  14931. // Let's disable the texture
  14932. texture._isDisabled = true;
  14933. }
  14934. };
  14935. /**
  14936. * Updates a depth texture Comparison Mode and Function.
  14937. * If the comparison Function is equal to 0, the mode will be set to none.
  14938. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14939. * @param texture The texture to set the comparison function for
  14940. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14941. */
  14942. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14943. if (this.webGLVersion === 1) {
  14944. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14945. return;
  14946. }
  14947. var gl = this._gl;
  14948. if (texture.isCube) {
  14949. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14950. if (comparisonFunction === 0) {
  14951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14953. }
  14954. else {
  14955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14957. }
  14958. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14959. }
  14960. else {
  14961. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14962. if (comparisonFunction === 0) {
  14963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14965. }
  14966. else {
  14967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14969. }
  14970. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14971. }
  14972. texture._comparisonFunction = comparisonFunction;
  14973. };
  14974. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14975. var width = size.width || size;
  14976. var height = size.height || size;
  14977. internalTexture.baseWidth = width;
  14978. internalTexture.baseHeight = height;
  14979. internalTexture.width = width;
  14980. internalTexture.height = height;
  14981. internalTexture.isReady = true;
  14982. internalTexture.samples = 1;
  14983. internalTexture.generateMipMaps = false;
  14984. internalTexture._generateDepthBuffer = true;
  14985. internalTexture._generateStencilBuffer = generateStencil;
  14986. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14987. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14988. internalTexture._comparisonFunction = comparisonFunction;
  14989. var gl = this._gl;
  14990. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14991. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14992. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14993. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14994. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14995. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14996. if (comparisonFunction === 0) {
  14997. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14998. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14999. }
  15000. else {
  15001. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15002. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15003. }
  15004. };
  15005. /**
  15006. * Creates a depth stencil texture.
  15007. * This is only available in WebGL 2 or with the depth texture extension available.
  15008. * @param size The size of face edge in the texture.
  15009. * @param options The options defining the texture.
  15010. * @returns The texture
  15011. */
  15012. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15013. if (options.isCube) {
  15014. var width = size.width || size;
  15015. return this._createDepthStencilCubeTexture(width, options);
  15016. }
  15017. else {
  15018. return this._createDepthStencilTexture(size, options);
  15019. }
  15020. };
  15021. /**
  15022. * Creates a depth stencil texture.
  15023. * This is only available in WebGL 2 or with the depth texture extension available.
  15024. * @param size The size of face edge in the texture.
  15025. * @param options The options defining the texture.
  15026. * @returns The texture
  15027. */
  15028. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15029. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15030. if (!this._caps.depthTextureExtension) {
  15031. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15032. return internalTexture;
  15033. }
  15034. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15035. var gl = this._gl;
  15036. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15037. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15038. if (this.webGLVersion > 1) {
  15039. if (internalOptions.generateStencil) {
  15040. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15041. }
  15042. else {
  15043. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15044. }
  15045. }
  15046. else {
  15047. if (internalOptions.generateStencil) {
  15048. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15049. }
  15050. else {
  15051. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15052. }
  15053. }
  15054. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15055. return internalTexture;
  15056. };
  15057. /**
  15058. * Creates a depth stencil cube texture.
  15059. * This is only available in WebGL 2.
  15060. * @param size The size of face edge in the cube texture.
  15061. * @param options The options defining the cube texture.
  15062. * @returns The cube texture
  15063. */
  15064. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15065. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15066. internalTexture.isCube = true;
  15067. if (this.webGLVersion === 1) {
  15068. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15069. return internalTexture;
  15070. }
  15071. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15072. var gl = this._gl;
  15073. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15074. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15075. // Create the depth/stencil buffer
  15076. for (var face = 0; face < 6; face++) {
  15077. if (internalOptions.generateStencil) {
  15078. 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);
  15079. }
  15080. else {
  15081. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15082. }
  15083. }
  15084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15085. return internalTexture;
  15086. };
  15087. /**
  15088. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15089. * @param renderTarget The render target to set the frame buffer for
  15090. */
  15091. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15092. // Create the framebuffer
  15093. var internalTexture = renderTarget.getInternalTexture();
  15094. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15095. return;
  15096. }
  15097. var gl = this._gl;
  15098. var depthStencilTexture = renderTarget.depthStencilTexture;
  15099. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15100. if (depthStencilTexture.isCube) {
  15101. if (depthStencilTexture._generateStencilBuffer) {
  15102. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15103. }
  15104. else {
  15105. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15106. }
  15107. }
  15108. else {
  15109. if (depthStencilTexture._generateStencilBuffer) {
  15110. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15111. }
  15112. else {
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15114. }
  15115. }
  15116. this.bindUnboundFramebuffer(null);
  15117. };
  15118. /**
  15119. * Creates a new render target texture
  15120. * @param size defines the size of the texture
  15121. * @param options defines the options used to create the texture
  15122. * @returns a new render target texture stored in an InternalTexture
  15123. */
  15124. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15125. var fullOptions = new RenderTargetCreationOptions();
  15126. if (options !== undefined && typeof options === "object") {
  15127. fullOptions.generateMipMaps = options.generateMipMaps;
  15128. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15129. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15130. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15131. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15132. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15133. }
  15134. else {
  15135. fullOptions.generateMipMaps = options;
  15136. fullOptions.generateDepthBuffer = true;
  15137. fullOptions.generateStencilBuffer = false;
  15138. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15139. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15140. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15141. }
  15142. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15143. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15144. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15145. }
  15146. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15147. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15148. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15149. }
  15150. var gl = this._gl;
  15151. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15152. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15153. var width = size.width || size;
  15154. var height = size.height || size;
  15155. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15156. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15157. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15158. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15159. }
  15160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15164. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15165. // Create the framebuffer
  15166. var framebuffer = gl.createFramebuffer();
  15167. this.bindUnboundFramebuffer(framebuffer);
  15168. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15169. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15170. if (fullOptions.generateMipMaps) {
  15171. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15172. }
  15173. // Unbind
  15174. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15175. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15176. this.bindUnboundFramebuffer(null);
  15177. texture._framebuffer = framebuffer;
  15178. texture.baseWidth = width;
  15179. texture.baseHeight = height;
  15180. texture.width = width;
  15181. texture.height = height;
  15182. texture.isReady = true;
  15183. texture.samples = 1;
  15184. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15185. texture.samplingMode = fullOptions.samplingMode;
  15186. texture.type = fullOptions.type;
  15187. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15188. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15189. // this.resetTextureCache();
  15190. this._internalTexturesCache.push(texture);
  15191. return texture;
  15192. };
  15193. /**
  15194. * Create a multi render target texture
  15195. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15196. * @param size defines the size of the texture
  15197. * @param options defines the creation options
  15198. * @returns the cube texture as an InternalTexture
  15199. */
  15200. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15201. var generateMipMaps = false;
  15202. var generateDepthBuffer = true;
  15203. var generateStencilBuffer = false;
  15204. var generateDepthTexture = false;
  15205. var textureCount = 1;
  15206. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15207. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15208. var types = new Array();
  15209. var samplingModes = new Array();
  15210. if (options !== undefined) {
  15211. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15212. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15213. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15214. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15215. textureCount = options.textureCount || 1;
  15216. if (options.types) {
  15217. types = options.types;
  15218. }
  15219. if (options.samplingModes) {
  15220. samplingModes = options.samplingModes;
  15221. }
  15222. }
  15223. var gl = this._gl;
  15224. // Create the framebuffer
  15225. var framebuffer = gl.createFramebuffer();
  15226. this.bindUnboundFramebuffer(framebuffer);
  15227. var width = size.width || size;
  15228. var height = size.height || size;
  15229. var textures = [];
  15230. var attachments = [];
  15231. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15232. for (var i = 0; i < textureCount; i++) {
  15233. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15234. var type = types[i] || defaultType;
  15235. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15236. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15237. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15238. }
  15239. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15240. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15241. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15242. }
  15243. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15244. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15245. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15246. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15247. }
  15248. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15249. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15250. textures.push(texture);
  15251. attachments.push(attachment);
  15252. gl.activeTexture(gl["TEXTURE" + i]);
  15253. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15258. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15259. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15260. if (generateMipMaps) {
  15261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15262. }
  15263. // Unbind
  15264. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15265. texture._framebuffer = framebuffer;
  15266. texture._depthStencilBuffer = depthStencilBuffer;
  15267. texture.baseWidth = width;
  15268. texture.baseHeight = height;
  15269. texture.width = width;
  15270. texture.height = height;
  15271. texture.isReady = true;
  15272. texture.samples = 1;
  15273. texture.generateMipMaps = generateMipMaps;
  15274. texture.samplingMode = samplingMode;
  15275. texture.type = type;
  15276. texture._generateDepthBuffer = generateDepthBuffer;
  15277. texture._generateStencilBuffer = generateStencilBuffer;
  15278. texture._attachments = attachments;
  15279. this._internalTexturesCache.push(texture);
  15280. }
  15281. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15282. // Depth texture
  15283. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15284. gl.activeTexture(gl.TEXTURE0);
  15285. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15290. 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);
  15291. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15292. depthTexture._framebuffer = framebuffer;
  15293. depthTexture.baseWidth = width;
  15294. depthTexture.baseHeight = height;
  15295. depthTexture.width = width;
  15296. depthTexture.height = height;
  15297. depthTexture.isReady = true;
  15298. depthTexture.samples = 1;
  15299. depthTexture.generateMipMaps = generateMipMaps;
  15300. depthTexture.samplingMode = gl.NEAREST;
  15301. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15302. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15303. textures.push(depthTexture);
  15304. this._internalTexturesCache.push(depthTexture);
  15305. }
  15306. gl.drawBuffers(attachments);
  15307. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15308. this.bindUnboundFramebuffer(null);
  15309. this.resetTextureCache();
  15310. return textures;
  15311. };
  15312. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15313. if (samples === void 0) { samples = 1; }
  15314. var depthStencilBuffer = null;
  15315. var gl = this._gl;
  15316. // Create the depth/stencil buffer
  15317. if (generateStencilBuffer) {
  15318. depthStencilBuffer = gl.createRenderbuffer();
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15320. if (samples > 1) {
  15321. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15322. }
  15323. else {
  15324. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15325. }
  15326. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15327. }
  15328. else if (generateDepthBuffer) {
  15329. depthStencilBuffer = gl.createRenderbuffer();
  15330. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15331. if (samples > 1) {
  15332. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15333. }
  15334. else {
  15335. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15336. }
  15337. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15338. }
  15339. return depthStencilBuffer;
  15340. };
  15341. /**
  15342. * Updates the sample count of a render target texture
  15343. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15344. * @param texture defines the texture to update
  15345. * @param samples defines the sample count to set
  15346. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15347. */
  15348. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15349. if (this.webGLVersion < 2 || !texture) {
  15350. return 1;
  15351. }
  15352. if (texture.samples === samples) {
  15353. return samples;
  15354. }
  15355. var gl = this._gl;
  15356. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15357. // Dispose previous render buffers
  15358. if (texture._depthStencilBuffer) {
  15359. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15360. texture._depthStencilBuffer = null;
  15361. }
  15362. if (texture._MSAAFramebuffer) {
  15363. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15364. texture._MSAAFramebuffer = null;
  15365. }
  15366. if (texture._MSAARenderBuffer) {
  15367. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15368. texture._MSAARenderBuffer = null;
  15369. }
  15370. if (samples > 1) {
  15371. var framebuffer = gl.createFramebuffer();
  15372. if (!framebuffer) {
  15373. throw new Error("Unable to create multi sampled framebuffer");
  15374. }
  15375. texture._MSAAFramebuffer = framebuffer;
  15376. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15377. var colorRenderbuffer = gl.createRenderbuffer();
  15378. if (!colorRenderbuffer) {
  15379. throw new Error("Unable to create multi sampled framebuffer");
  15380. }
  15381. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15382. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15383. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15384. texture._MSAARenderBuffer = colorRenderbuffer;
  15385. }
  15386. else {
  15387. this.bindUnboundFramebuffer(texture._framebuffer);
  15388. }
  15389. texture.samples = samples;
  15390. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15391. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15392. this.bindUnboundFramebuffer(null);
  15393. return samples;
  15394. };
  15395. /**
  15396. * Update the sample count for a given multiple render target texture
  15397. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15398. * @param textures defines the textures to update
  15399. * @param samples defines the sample count to set
  15400. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15401. */
  15402. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15403. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15404. return 1;
  15405. }
  15406. if (textures[0].samples === samples) {
  15407. return samples;
  15408. }
  15409. var gl = this._gl;
  15410. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15411. // Dispose previous render buffers
  15412. if (textures[0]._depthStencilBuffer) {
  15413. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15414. textures[0]._depthStencilBuffer = null;
  15415. }
  15416. if (textures[0]._MSAAFramebuffer) {
  15417. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15418. textures[0]._MSAAFramebuffer = null;
  15419. }
  15420. for (var i = 0; i < textures.length; i++) {
  15421. if (textures[i]._MSAARenderBuffer) {
  15422. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15423. textures[i]._MSAARenderBuffer = null;
  15424. }
  15425. }
  15426. if (samples > 1) {
  15427. var framebuffer = gl.createFramebuffer();
  15428. if (!framebuffer) {
  15429. throw new Error("Unable to create multi sampled framebuffer");
  15430. }
  15431. this.bindUnboundFramebuffer(framebuffer);
  15432. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15433. var attachments = [];
  15434. for (var i = 0; i < textures.length; i++) {
  15435. var texture = textures[i];
  15436. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15437. var colorRenderbuffer = gl.createRenderbuffer();
  15438. if (!colorRenderbuffer) {
  15439. throw new Error("Unable to create multi sampled framebuffer");
  15440. }
  15441. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15442. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15443. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15444. texture._MSAAFramebuffer = framebuffer;
  15445. texture._MSAARenderBuffer = colorRenderbuffer;
  15446. texture.samples = samples;
  15447. texture._depthStencilBuffer = depthStencilBuffer;
  15448. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15449. attachments.push(attachment);
  15450. }
  15451. gl.drawBuffers(attachments);
  15452. }
  15453. else {
  15454. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15455. }
  15456. this.bindUnboundFramebuffer(null);
  15457. return samples;
  15458. };
  15459. /** @hidden */
  15460. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15461. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15462. };
  15463. /** @hidden */
  15464. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15465. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15466. };
  15467. /**
  15468. * Creates a new render target cube texture
  15469. * @param size defines the size of the texture
  15470. * @param options defines the options used to create the texture
  15471. * @returns a new render target cube texture stored in an InternalTexture
  15472. */
  15473. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15474. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15475. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15476. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15477. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15478. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15479. }
  15480. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15481. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15482. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15483. }
  15484. var gl = this._gl;
  15485. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15486. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15487. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15488. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15489. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15490. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15491. }
  15492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15496. for (var face = 0; face < 6; face++) {
  15497. 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);
  15498. }
  15499. // Create the framebuffer
  15500. var framebuffer = gl.createFramebuffer();
  15501. this.bindUnboundFramebuffer(framebuffer);
  15502. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15503. // MipMaps
  15504. if (fullOptions.generateMipMaps) {
  15505. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15506. }
  15507. // Unbind
  15508. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15509. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15510. this.bindUnboundFramebuffer(null);
  15511. texture._framebuffer = framebuffer;
  15512. texture.width = size;
  15513. texture.height = size;
  15514. texture.isReady = true;
  15515. texture.isCube = true;
  15516. texture.samples = 1;
  15517. texture.generateMipMaps = fullOptions.generateMipMaps;
  15518. texture.samplingMode = fullOptions.samplingMode;
  15519. texture.type = fullOptions.type;
  15520. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15521. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15522. this._internalTexturesCache.push(texture);
  15523. return texture;
  15524. };
  15525. /**
  15526. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15527. * @param rootUrl defines the url where the file to load is located
  15528. * @param scene defines the current scene
  15529. * @param scale defines scale to apply to the mip map selection
  15530. * @param offset defines offset to apply to the mip map selection
  15531. * @param onLoad defines an optional callback raised when the texture is loaded
  15532. * @param onError defines an optional callback raised if there is an issue to load the texture
  15533. * @param format defines the format of the data
  15534. * @param forcedExtension defines the extension to use to pick the right loader
  15535. * @returns the cube texture as an InternalTexture
  15536. */
  15537. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15538. var _this = this;
  15539. if (onLoad === void 0) { onLoad = null; }
  15540. if (onError === void 0) { onError = null; }
  15541. if (forcedExtension === void 0) { forcedExtension = null; }
  15542. var callback = function (loadData) {
  15543. if (!loadData) {
  15544. if (onLoad) {
  15545. onLoad(null);
  15546. }
  15547. return;
  15548. }
  15549. var texture = loadData.texture;
  15550. if (loadData.info.sphericalPolynomial) {
  15551. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15552. }
  15553. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15554. texture._lodGenerationScale = scale;
  15555. texture._lodGenerationOffset = offset;
  15556. if (_this._caps.textureLOD) {
  15557. // Do not add extra process if texture lod is supported.
  15558. if (onLoad) {
  15559. onLoad(texture);
  15560. }
  15561. return;
  15562. }
  15563. var mipSlices = 3;
  15564. var gl = _this._gl;
  15565. var width = loadData.width;
  15566. if (!width) {
  15567. return;
  15568. }
  15569. var textures = [];
  15570. for (var i = 0; i < mipSlices; i++) {
  15571. //compute LOD from even spacing in smoothness (matching shader calculation)
  15572. var smoothness = i / (mipSlices - 1);
  15573. var roughness = 1 - smoothness;
  15574. var minLODIndex = offset; // roughness = 0
  15575. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15576. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15577. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15578. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15579. glTextureFromLod.isCube = true;
  15580. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15581. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15585. if (loadData.isDDS) {
  15586. var info = loadData.info;
  15587. var data = loadData.data;
  15588. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15589. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15590. }
  15591. else {
  15592. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15593. }
  15594. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15595. // Wrap in a base texture for easy binding.
  15596. var lodTexture = new BABYLON.BaseTexture(scene);
  15597. lodTexture.isCube = true;
  15598. lodTexture._texture = glTextureFromLod;
  15599. glTextureFromLod.isReady = true;
  15600. textures.push(lodTexture);
  15601. }
  15602. texture._lodTextureHigh = textures[2];
  15603. texture._lodTextureMid = textures[1];
  15604. texture._lodTextureLow = textures[0];
  15605. if (onLoad) {
  15606. onLoad(texture);
  15607. }
  15608. };
  15609. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15610. };
  15611. /**
  15612. * Creates a cube texture
  15613. * @param rootUrl defines the url where the files to load is located
  15614. * @param scene defines the current scene
  15615. * @param files defines the list of files to load (1 per face)
  15616. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15617. * @param onLoad defines an optional callback raised when the texture is loaded
  15618. * @param onError defines an optional callback raised if there is an issue to load the texture
  15619. * @param format defines the format of the data
  15620. * @param forcedExtension defines the extension to use to pick the right loader
  15621. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15622. * @returns the cube texture as an InternalTexture
  15623. */
  15624. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15625. var _this = this;
  15626. if (onLoad === void 0) { onLoad = null; }
  15627. if (onError === void 0) { onError = null; }
  15628. if (forcedExtension === void 0) { forcedExtension = null; }
  15629. if (createPolynomials === void 0) { createPolynomials = false; }
  15630. var gl = this._gl;
  15631. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15632. texture.isCube = true;
  15633. texture.url = rootUrl;
  15634. texture.generateMipMaps = !noMipmap;
  15635. if (!this._doNotHandleContextLost) {
  15636. texture._extension = forcedExtension;
  15637. texture._files = files;
  15638. }
  15639. var isKTX = false;
  15640. var isDDS = false;
  15641. var lastDot = rootUrl.lastIndexOf('.');
  15642. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15643. if (this._textureFormatInUse) {
  15644. extension = this._textureFormatInUse;
  15645. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15646. isKTX = true;
  15647. }
  15648. else {
  15649. isDDS = (extension === ".dds");
  15650. }
  15651. var onerror = function (request, exception) {
  15652. if (onError && request) {
  15653. onError(request.status + " " + request.statusText, exception);
  15654. }
  15655. };
  15656. if (isKTX) {
  15657. this._loadFile(rootUrl, function (data) {
  15658. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15659. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15660. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15661. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15662. ktx.uploadLevels(_this._gl, !noMipmap);
  15663. _this.setCubeMapTextureParams(gl, loadMipmap);
  15664. texture.width = ktx.pixelWidth;
  15665. texture.height = ktx.pixelHeight;
  15666. texture.isReady = true;
  15667. }, undefined, undefined, true, onerror);
  15668. }
  15669. else if (isDDS) {
  15670. if (files && files.length === 6) {
  15671. this._cascadeLoadFiles(scene, function (imgs) {
  15672. var info;
  15673. var loadMipmap = false;
  15674. var width = 0;
  15675. for (var index = 0; index < imgs.length; index++) {
  15676. var data = imgs[index];
  15677. info = BABYLON.DDSTools.GetDDSInfo(data);
  15678. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15679. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15680. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15681. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15682. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15683. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15684. }
  15685. texture.width = info.width;
  15686. texture.height = info.height;
  15687. texture.type = info.textureType;
  15688. width = info.width;
  15689. }
  15690. _this.setCubeMapTextureParams(gl, loadMipmap);
  15691. texture.isReady = true;
  15692. if (onLoad) {
  15693. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15694. }
  15695. }, files, onError);
  15696. }
  15697. else {
  15698. this._loadFile(rootUrl, function (data) {
  15699. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15700. if (createPolynomials) {
  15701. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15702. }
  15703. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15705. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15706. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15707. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15708. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15709. }
  15710. _this.setCubeMapTextureParams(gl, loadMipmap);
  15711. texture.width = info.width;
  15712. texture.height = info.height;
  15713. texture.isReady = true;
  15714. texture.type = info.textureType;
  15715. if (onLoad) {
  15716. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15717. }
  15718. }, undefined, undefined, true, onerror);
  15719. }
  15720. }
  15721. else {
  15722. if (!files) {
  15723. throw new Error("Cannot load cubemap because files were not defined");
  15724. }
  15725. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15726. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15727. var height = width;
  15728. _this._prepareWorkingCanvas();
  15729. if (!_this._workingCanvas || !_this._workingContext) {
  15730. return;
  15731. }
  15732. _this._workingCanvas.width = width;
  15733. _this._workingCanvas.height = height;
  15734. var faces = [
  15735. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15736. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15737. ];
  15738. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15740. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15741. for (var index = 0; index < faces.length; index++) {
  15742. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15743. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15744. }
  15745. if (!noMipmap) {
  15746. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15747. }
  15748. _this.setCubeMapTextureParams(gl, !noMipmap);
  15749. texture.width = width;
  15750. texture.height = height;
  15751. texture.isReady = true;
  15752. if (format) {
  15753. texture.format = format;
  15754. }
  15755. texture.onLoadedObservable.notifyObservers(texture);
  15756. texture.onLoadedObservable.clear();
  15757. if (onLoad) {
  15758. onLoad();
  15759. }
  15760. }, files, onError);
  15761. }
  15762. this._internalTexturesCache.push(texture);
  15763. return texture;
  15764. };
  15765. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15770. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15771. // this.resetTextureCache();
  15772. };
  15773. /**
  15774. * Update a raw cube texture
  15775. * @param texture defines the texture to udpdate
  15776. * @param data defines the data to store
  15777. * @param format defines the data format
  15778. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15779. * @param invertY defines if data must be stored with Y axis inverted
  15780. * @param compression defines the compression used (null by default)
  15781. * @param level defines which level of the texture to update
  15782. */
  15783. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15784. if (compression === void 0) { compression = null; }
  15785. if (level === void 0) { level = 0; }
  15786. texture._bufferViewArray = data;
  15787. texture.format = format;
  15788. texture.type = type;
  15789. texture.invertY = invertY;
  15790. texture._compression = compression;
  15791. var gl = this._gl;
  15792. var textureType = this._getWebGLTextureType(type);
  15793. var internalFormat = this._getInternalFormat(format);
  15794. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15795. var needConversion = false;
  15796. if (internalFormat === gl.RGB) {
  15797. internalFormat = gl.RGBA;
  15798. needConversion = true;
  15799. }
  15800. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15801. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15802. if (texture.width % 4 !== 0) {
  15803. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15804. }
  15805. // Data are known to be in +X +Y +Z -X -Y -Z
  15806. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15807. var faceData = data[faceIndex];
  15808. if (compression) {
  15809. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15810. }
  15811. else {
  15812. if (needConversion) {
  15813. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15814. }
  15815. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15816. }
  15817. }
  15818. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15819. if (isPot && texture.generateMipMaps && level === 0) {
  15820. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15821. }
  15822. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15823. // this.resetTextureCache();
  15824. texture.isReady = true;
  15825. };
  15826. /**
  15827. * Creates a new raw cube texture
  15828. * @param data defines the array of data to use to create each face
  15829. * @param size defines the size of the textures
  15830. * @param format defines the format of the data
  15831. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15832. * @param generateMipMaps defines if the engine should generate the mip levels
  15833. * @param invertY defines if data must be stored with Y axis inverted
  15834. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15835. * @param compression defines the compression used (null by default)
  15836. * @returns the cube texture as an InternalTexture
  15837. */
  15838. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15839. if (compression === void 0) { compression = null; }
  15840. var gl = this._gl;
  15841. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15842. texture.isCube = true;
  15843. texture.generateMipMaps = generateMipMaps;
  15844. texture.format = format;
  15845. texture.type = type;
  15846. if (!this._doNotHandleContextLost) {
  15847. texture._bufferViewArray = data;
  15848. }
  15849. var textureType = this._getWebGLTextureType(type);
  15850. var internalFormat = this._getInternalFormat(format);
  15851. if (internalFormat === gl.RGB) {
  15852. internalFormat = gl.RGBA;
  15853. }
  15854. var width = size;
  15855. var height = width;
  15856. texture.width = width;
  15857. texture.height = height;
  15858. // Double check on POT to generate Mips.
  15859. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15860. if (!isPot) {
  15861. generateMipMaps = false;
  15862. }
  15863. // Upload data if needed. The texture won't be ready until then.
  15864. if (data) {
  15865. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15866. }
  15867. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15868. // Filters
  15869. if (data && generateMipMaps) {
  15870. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15871. }
  15872. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15875. }
  15876. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15879. }
  15880. else {
  15881. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15884. }
  15885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15887. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15888. return texture;
  15889. };
  15890. /**
  15891. * Creates a new raw cube texture from a specified url
  15892. * @param url defines the url where the data is located
  15893. * @param scene defines the current scene
  15894. * @param size defines the size of the textures
  15895. * @param format defines the format of the data
  15896. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15897. * @param noMipmap defines if the engine should avoid generating the mip levels
  15898. * @param callback defines a callback used to extract texture data from loaded data
  15899. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15900. * @param onLoad defines a callback called when texture is loaded
  15901. * @param onError defines a callback called if there is an error
  15902. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15903. * @param invertY defines if data must be stored with Y axis inverted
  15904. * @returns the cube texture as an InternalTexture
  15905. */
  15906. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15907. var _this = this;
  15908. if (onLoad === void 0) { onLoad = null; }
  15909. if (onError === void 0) { onError = null; }
  15910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15911. if (invertY === void 0) { invertY = false; }
  15912. var gl = this._gl;
  15913. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15914. scene._addPendingData(texture);
  15915. texture.url = url;
  15916. this._internalTexturesCache.push(texture);
  15917. var onerror = function (request, exception) {
  15918. scene._removePendingData(texture);
  15919. if (onError && request) {
  15920. onError(request.status + " " + request.statusText, exception);
  15921. }
  15922. };
  15923. var internalCallback = function (data) {
  15924. var width = texture.width;
  15925. var faceDataArrays = callback(data);
  15926. if (!faceDataArrays) {
  15927. return;
  15928. }
  15929. if (mipmapGenerator) {
  15930. var textureType = _this._getWebGLTextureType(type);
  15931. var internalFormat = _this._getInternalFormat(format);
  15932. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15933. var needConversion = false;
  15934. if (internalFormat === gl.RGB) {
  15935. internalFormat = gl.RGBA;
  15936. needConversion = true;
  15937. }
  15938. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15939. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15940. var mipData = mipmapGenerator(faceDataArrays);
  15941. for (var level = 0; level < mipData.length; level++) {
  15942. var mipSize = width >> level;
  15943. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15944. var mipFaceData = mipData[level][faceIndex];
  15945. if (needConversion) {
  15946. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15947. }
  15948. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15949. }
  15950. }
  15951. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15952. }
  15953. else {
  15954. texture.generateMipMaps = !noMipmap;
  15955. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15956. }
  15957. texture.isReady = true;
  15958. // this.resetTextureCache();
  15959. scene._removePendingData(texture);
  15960. if (onLoad) {
  15961. onLoad();
  15962. }
  15963. };
  15964. this._loadFile(url, function (data) {
  15965. internalCallback(data);
  15966. }, undefined, scene.database, true, onerror);
  15967. return texture;
  15968. };
  15969. ;
  15970. /**
  15971. * Update a raw 3D texture
  15972. * @param texture defines the texture to update
  15973. * @param data defines the data to store
  15974. * @param format defines the data format
  15975. * @param invertY defines if data must be stored with Y axis inverted
  15976. * @param compression defines the used compression (can be null)
  15977. */
  15978. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15979. if (compression === void 0) { compression = null; }
  15980. var internalFormat = this._getInternalFormat(format);
  15981. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15982. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15983. if (!this._doNotHandleContextLost) {
  15984. texture._bufferView = data;
  15985. texture.format = format;
  15986. texture.invertY = invertY;
  15987. texture._compression = compression;
  15988. }
  15989. if (texture.width % 4 !== 0) {
  15990. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15991. }
  15992. if (compression && data) {
  15993. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15994. }
  15995. else {
  15996. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15997. }
  15998. if (texture.generateMipMaps) {
  15999. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16000. }
  16001. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16002. // this.resetTextureCache();
  16003. texture.isReady = true;
  16004. };
  16005. /**
  16006. * Creates a new raw 3D texture
  16007. * @param data defines the data used to create the texture
  16008. * @param width defines the width of the texture
  16009. * @param height defines the height of the texture
  16010. * @param depth defines the depth of the texture
  16011. * @param format defines the format of the texture
  16012. * @param generateMipMaps defines if the engine must generate mip levels
  16013. * @param invertY defines if data must be stored with Y axis inverted
  16014. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16015. * @param compression defines the compressed used (can be null)
  16016. * @returns a new raw 3D texture (stored in an InternalTexture)
  16017. */
  16018. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16019. if (compression === void 0) { compression = null; }
  16020. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16021. texture.baseWidth = width;
  16022. texture.baseHeight = height;
  16023. texture.baseDepth = depth;
  16024. texture.width = width;
  16025. texture.height = height;
  16026. texture.depth = depth;
  16027. texture.format = format;
  16028. texture.generateMipMaps = generateMipMaps;
  16029. texture.samplingMode = samplingMode;
  16030. texture.is3D = true;
  16031. if (!this._doNotHandleContextLost) {
  16032. texture._bufferView = data;
  16033. }
  16034. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16035. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16036. // Filters
  16037. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16038. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16039. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16040. if (generateMipMaps) {
  16041. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16042. }
  16043. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16044. this._internalTexturesCache.push(texture);
  16045. return texture;
  16046. };
  16047. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16048. var gl = this._gl;
  16049. if (!gl) {
  16050. return;
  16051. }
  16052. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16053. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16054. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16055. if (!noMipmap && !isCompressed) {
  16056. gl.generateMipmap(gl.TEXTURE_2D);
  16057. }
  16058. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16059. // this.resetTextureCache();
  16060. if (scene) {
  16061. scene._removePendingData(texture);
  16062. }
  16063. texture.onLoadedObservable.notifyObservers(texture);
  16064. texture.onLoadedObservable.clear();
  16065. };
  16066. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16067. var _this = this;
  16068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16069. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16070. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16071. var gl = this._gl;
  16072. if (!gl) {
  16073. return;
  16074. }
  16075. if (!texture._webGLTexture) {
  16076. // this.resetTextureCache();
  16077. if (scene) {
  16078. scene._removePendingData(texture);
  16079. }
  16080. return;
  16081. }
  16082. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16083. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16084. texture.baseWidth = width;
  16085. texture.baseHeight = height;
  16086. texture.width = potWidth;
  16087. texture.height = potHeight;
  16088. texture.isReady = true;
  16089. if (processFunction(potWidth, potHeight, function () {
  16090. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16091. })) {
  16092. // Returning as texture needs extra async steps
  16093. return;
  16094. }
  16095. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16096. };
  16097. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16098. // Create new RGBA data container.
  16099. var rgbaData;
  16100. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16101. rgbaData = new Float32Array(width * height * 4);
  16102. }
  16103. else {
  16104. rgbaData = new Uint32Array(width * height * 4);
  16105. }
  16106. // Convert each pixel.
  16107. for (var x = 0; x < width; x++) {
  16108. for (var y = 0; y < height; y++) {
  16109. var index = (y * width + x) * 3;
  16110. var newIndex = (y * width + x) * 4;
  16111. // Map Old Value to new value.
  16112. rgbaData[newIndex + 0] = rgbData[index + 0];
  16113. rgbaData[newIndex + 1] = rgbData[index + 1];
  16114. rgbaData[newIndex + 2] = rgbData[index + 2];
  16115. // Add fully opaque alpha channel.
  16116. rgbaData[newIndex + 3] = 1;
  16117. }
  16118. }
  16119. return rgbaData;
  16120. };
  16121. /** @hidden */
  16122. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16123. var gl = this._gl;
  16124. if (texture._framebuffer) {
  16125. gl.deleteFramebuffer(texture._framebuffer);
  16126. texture._framebuffer = null;
  16127. }
  16128. if (texture._depthStencilBuffer) {
  16129. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16130. texture._depthStencilBuffer = null;
  16131. }
  16132. if (texture._MSAAFramebuffer) {
  16133. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16134. texture._MSAAFramebuffer = null;
  16135. }
  16136. if (texture._MSAARenderBuffer) {
  16137. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16138. texture._MSAARenderBuffer = null;
  16139. }
  16140. };
  16141. /** @hidden */
  16142. Engine.prototype._releaseTexture = function (texture) {
  16143. var gl = this._gl;
  16144. this._releaseFramebufferObjects(texture);
  16145. gl.deleteTexture(texture._webGLTexture);
  16146. // Unbind channels
  16147. this.unbindAllTextures();
  16148. var index = this._internalTexturesCache.indexOf(texture);
  16149. if (index !== -1) {
  16150. this._internalTexturesCache.splice(index, 1);
  16151. }
  16152. // Integrated fixed lod samplers.
  16153. if (texture._lodTextureHigh) {
  16154. texture._lodTextureHigh.dispose();
  16155. }
  16156. if (texture._lodTextureMid) {
  16157. texture._lodTextureMid.dispose();
  16158. }
  16159. if (texture._lodTextureLow) {
  16160. texture._lodTextureLow.dispose();
  16161. }
  16162. // Set output texture of post process to null if the texture has been released/disposed
  16163. this.scenes.forEach(function (scene) {
  16164. scene.postProcesses.forEach(function (postProcess) {
  16165. if (postProcess._outputTexture == texture) {
  16166. postProcess._outputTexture = null;
  16167. }
  16168. });
  16169. scene.cameras.forEach(function (camera) {
  16170. camera._postProcesses.forEach(function (postProcess) {
  16171. if (postProcess) {
  16172. if (postProcess._outputTexture == texture) {
  16173. postProcess._outputTexture = null;
  16174. }
  16175. }
  16176. });
  16177. });
  16178. });
  16179. };
  16180. Engine.prototype.setProgram = function (program) {
  16181. if (this._currentProgram !== program) {
  16182. this._gl.useProgram(program);
  16183. this._currentProgram = program;
  16184. }
  16185. };
  16186. /**
  16187. * Binds an effect to the webGL context
  16188. * @param effect defines the effect to bind
  16189. */
  16190. Engine.prototype.bindSamplers = function (effect) {
  16191. this.setProgram(effect.getProgram());
  16192. var samplers = effect.getSamplers();
  16193. for (var index = 0; index < samplers.length; index++) {
  16194. var uniform = effect.getUniform(samplers[index]);
  16195. if (uniform) {
  16196. this._boundUniforms[index] = uniform;
  16197. }
  16198. }
  16199. this._currentEffect = null;
  16200. };
  16201. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16202. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16203. return;
  16204. }
  16205. // Remove
  16206. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16207. // Bind last to it
  16208. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16209. // Bind to dummy
  16210. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16211. };
  16212. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16213. if (!internalTexture) {
  16214. return -1;
  16215. }
  16216. internalTexture._initialSlot = channel;
  16217. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16218. if (channel !== internalTexture._designatedSlot) {
  16219. this._textureCollisions.addCount(1, false);
  16220. }
  16221. }
  16222. else {
  16223. if (channel !== internalTexture._designatedSlot) {
  16224. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16225. return internalTexture._designatedSlot;
  16226. }
  16227. else {
  16228. // No slot for this texture, let's pick a new one (if we find a free slot)
  16229. if (this._nextFreeTextureSlots.length) {
  16230. return this._nextFreeTextureSlots[0];
  16231. }
  16232. // We need to recycle the oldest bound texture, sorry.
  16233. this._textureCollisions.addCount(1, false);
  16234. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16235. }
  16236. }
  16237. }
  16238. return channel;
  16239. };
  16240. Engine.prototype._linkTrackers = function (previous, next) {
  16241. previous.next = next;
  16242. next.previous = previous;
  16243. };
  16244. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16245. var currentSlot = internalTexture._designatedSlot;
  16246. if (currentSlot === -1) {
  16247. return -1;
  16248. }
  16249. internalTexture._designatedSlot = -1;
  16250. if (this.disableTextureBindingOptimization) {
  16251. return -1;
  16252. }
  16253. // Remove from bound list
  16254. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16255. // Free the slot
  16256. this._boundTexturesCache[currentSlot] = null;
  16257. this._nextFreeTextureSlots.push(currentSlot);
  16258. return currentSlot;
  16259. };
  16260. Engine.prototype._activateCurrentTexture = function () {
  16261. if (this._currentTextureChannel !== this._activeChannel) {
  16262. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16263. this._currentTextureChannel = this._activeChannel;
  16264. }
  16265. };
  16266. /** @hidden */
  16267. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16268. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16269. if (force === void 0) { force = false; }
  16270. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16271. this._activeChannel = texture._designatedSlot;
  16272. }
  16273. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16274. var isTextureForRendering = texture && texture._initialSlot > -1;
  16275. if (currentTextureBound !== texture || force) {
  16276. if (currentTextureBound) {
  16277. this._removeDesignatedSlot(currentTextureBound);
  16278. }
  16279. this._activateCurrentTexture();
  16280. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16281. this._boundTexturesCache[this._activeChannel] = texture;
  16282. if (texture) {
  16283. if (!this.disableTextureBindingOptimization) {
  16284. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16285. if (slotIndex > -1) {
  16286. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16287. }
  16288. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16289. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16290. }
  16291. texture._designatedSlot = this._activeChannel;
  16292. }
  16293. }
  16294. else if (forTextureDataUpdate) {
  16295. this._activateCurrentTexture();
  16296. }
  16297. if (isTextureForRendering && !forTextureDataUpdate) {
  16298. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16299. }
  16300. };
  16301. /** @hidden */
  16302. Engine.prototype._bindTexture = function (channel, texture) {
  16303. if (channel < 0) {
  16304. return;
  16305. }
  16306. if (texture) {
  16307. channel = this._getCorrectTextureChannel(channel, texture);
  16308. }
  16309. this._activeChannel = channel;
  16310. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16311. };
  16312. /**
  16313. * Sets a texture to the webGL context from a postprocess
  16314. * @param channel defines the channel to use
  16315. * @param postProcess defines the source postprocess
  16316. */
  16317. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16318. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16319. };
  16320. /**
  16321. * Binds the output of the passed in post process to the texture channel specified
  16322. * @param channel The channel the texture should be bound to
  16323. * @param postProcess The post process which's output should be bound
  16324. */
  16325. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16326. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16327. };
  16328. /**
  16329. * Unbind all textures from the webGL context
  16330. */
  16331. Engine.prototype.unbindAllTextures = function () {
  16332. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16333. this._activeChannel = channel;
  16334. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16335. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16336. if (this.webGLVersion > 1) {
  16337. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16338. }
  16339. }
  16340. };
  16341. /**
  16342. * Sets a texture to the according uniform.
  16343. * @param channel The texture channel
  16344. * @param uniform The uniform to set
  16345. * @param texture The texture to apply
  16346. */
  16347. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16348. if (channel < 0) {
  16349. return;
  16350. }
  16351. if (uniform) {
  16352. this._boundUniforms[channel] = uniform;
  16353. }
  16354. this._setTexture(channel, texture);
  16355. };
  16356. /**
  16357. * Sets a depth stencil texture from a render target to the according uniform.
  16358. * @param channel The texture channel
  16359. * @param uniform The uniform to set
  16360. * @param texture The render target texture containing the depth stencil texture to apply
  16361. */
  16362. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16363. if (channel < 0) {
  16364. return;
  16365. }
  16366. if (uniform) {
  16367. this._boundUniforms[channel] = uniform;
  16368. }
  16369. if (!texture || !texture.depthStencilTexture) {
  16370. this._setTexture(channel, null);
  16371. }
  16372. else {
  16373. this._setTexture(channel, texture, false, true);
  16374. }
  16375. };
  16376. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16377. var uniform = this._boundUniforms[sourceSlot];
  16378. if (uniform._currentState === destination) {
  16379. return;
  16380. }
  16381. this._gl.uniform1i(uniform, destination);
  16382. uniform._currentState = destination;
  16383. };
  16384. Engine.prototype._getTextureWrapMode = function (mode) {
  16385. switch (mode) {
  16386. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16387. return this._gl.REPEAT;
  16388. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16389. return this._gl.CLAMP_TO_EDGE;
  16390. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16391. return this._gl.MIRRORED_REPEAT;
  16392. }
  16393. return this._gl.REPEAT;
  16394. };
  16395. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16396. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16397. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16398. // Not ready?
  16399. if (!texture) {
  16400. if (this._boundTexturesCache[channel] != null) {
  16401. this._activeChannel = channel;
  16402. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16403. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16404. if (this.webGLVersion > 1) {
  16405. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16406. }
  16407. }
  16408. return false;
  16409. }
  16410. // Video
  16411. if (texture.video) {
  16412. this._activeChannel = channel;
  16413. texture.update();
  16414. }
  16415. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16416. texture.delayLoad();
  16417. return false;
  16418. }
  16419. var internalTexture;
  16420. if (depthStencilTexture) {
  16421. internalTexture = texture.depthStencilTexture;
  16422. }
  16423. else if (texture.isReady()) {
  16424. internalTexture = texture.getInternalTexture();
  16425. }
  16426. else if (texture.isCube) {
  16427. internalTexture = this.emptyCubeTexture;
  16428. }
  16429. else if (texture.is3D) {
  16430. internalTexture = this.emptyTexture3D;
  16431. }
  16432. else {
  16433. internalTexture = this.emptyTexture;
  16434. }
  16435. if (!isPartOfTextureArray) {
  16436. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16437. }
  16438. var needToBind = true;
  16439. if (this._boundTexturesCache[channel] === internalTexture) {
  16440. this._moveBoundTextureOnTop(internalTexture);
  16441. if (!isPartOfTextureArray) {
  16442. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16443. }
  16444. needToBind = false;
  16445. }
  16446. this._activeChannel = channel;
  16447. if (internalTexture && internalTexture.is3D) {
  16448. if (needToBind) {
  16449. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16450. }
  16451. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16452. internalTexture._cachedWrapU = texture.wrapU;
  16453. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16454. }
  16455. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16456. internalTexture._cachedWrapV = texture.wrapV;
  16457. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16458. }
  16459. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16460. internalTexture._cachedWrapR = texture.wrapR;
  16461. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16462. }
  16463. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16464. }
  16465. else if (internalTexture && internalTexture.isCube) {
  16466. if (needToBind) {
  16467. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16468. }
  16469. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16470. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16471. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16472. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16473. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16474. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16475. }
  16476. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16477. }
  16478. else {
  16479. if (needToBind) {
  16480. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16481. }
  16482. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16483. internalTexture._cachedWrapU = texture.wrapU;
  16484. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16485. }
  16486. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16487. internalTexture._cachedWrapV = texture.wrapV;
  16488. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16489. }
  16490. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16491. }
  16492. return true;
  16493. };
  16494. /**
  16495. * Sets an array of texture to the webGL context
  16496. * @param channel defines the channel where the texture array must be set
  16497. * @param uniform defines the associated uniform location
  16498. * @param textures defines the array of textures to bind
  16499. */
  16500. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16501. if (channel < 0 || !uniform) {
  16502. return;
  16503. }
  16504. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16505. this._textureUnits = new Int32Array(textures.length);
  16506. }
  16507. for (var i = 0; i < textures.length; i++) {
  16508. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16509. }
  16510. this._gl.uniform1iv(uniform, this._textureUnits);
  16511. for (var index = 0; index < textures.length; index++) {
  16512. this._setTexture(this._textureUnits[index], textures[index], true);
  16513. }
  16514. };
  16515. /** @hidden */
  16516. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16517. var internalTexture = texture.getInternalTexture();
  16518. if (!internalTexture) {
  16519. return;
  16520. }
  16521. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16522. var value = texture.anisotropicFilteringLevel;
  16523. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16524. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16525. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16526. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16527. }
  16528. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16529. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16530. internalTexture._cachedAnisotropicFilteringLevel = value;
  16531. }
  16532. };
  16533. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16534. this._bindTextureDirectly(target, texture, true, true);
  16535. this._gl.texParameterf(target, parameter, value);
  16536. };
  16537. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16538. if (texture) {
  16539. this._bindTextureDirectly(target, texture, true, true);
  16540. }
  16541. this._gl.texParameteri(target, parameter, value);
  16542. };
  16543. /**
  16544. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16545. * @param x defines the x coordinate of the rectangle where pixels must be read
  16546. * @param y defines the y coordinate of the rectangle where pixels must be read
  16547. * @param width defines the width of the rectangle where pixels must be read
  16548. * @param height defines the height of the rectangle where pixels must be read
  16549. * @returns a Uint8Array containing RGBA colors
  16550. */
  16551. Engine.prototype.readPixels = function (x, y, width, height) {
  16552. var data = new Uint8Array(height * width * 4);
  16553. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16554. return data;
  16555. };
  16556. /**
  16557. * Add an externaly attached data from its key.
  16558. * This method call will fail and return false, if such key already exists.
  16559. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16560. * @param key the unique key that identifies the data
  16561. * @param data the data object to associate to the key for this Engine instance
  16562. * @return true if no such key were already present and the data was added successfully, false otherwise
  16563. */
  16564. Engine.prototype.addExternalData = function (key, data) {
  16565. if (!this._externalData) {
  16566. this._externalData = new BABYLON.StringDictionary();
  16567. }
  16568. return this._externalData.add(key, data);
  16569. };
  16570. /**
  16571. * Get an externaly attached data from its key
  16572. * @param key the unique key that identifies the data
  16573. * @return the associated data, if present (can be null), or undefined if not present
  16574. */
  16575. Engine.prototype.getExternalData = function (key) {
  16576. if (!this._externalData) {
  16577. this._externalData = new BABYLON.StringDictionary();
  16578. }
  16579. return this._externalData.get(key);
  16580. };
  16581. /**
  16582. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16583. * @param key the unique key that identifies the data
  16584. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16585. * @return the associated data, can be null if the factory returned null.
  16586. */
  16587. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16588. if (!this._externalData) {
  16589. this._externalData = new BABYLON.StringDictionary();
  16590. }
  16591. return this._externalData.getOrAddWithFactory(key, factory);
  16592. };
  16593. /**
  16594. * Remove an externaly attached data from the Engine instance
  16595. * @param key the unique key that identifies the data
  16596. * @return true if the data was successfully removed, false if it doesn't exist
  16597. */
  16598. Engine.prototype.removeExternalData = function (key) {
  16599. if (!this._externalData) {
  16600. this._externalData = new BABYLON.StringDictionary();
  16601. }
  16602. return this._externalData.remove(key);
  16603. };
  16604. /**
  16605. * Unbind all vertex attributes from the webGL context
  16606. */
  16607. Engine.prototype.unbindAllAttributes = function () {
  16608. if (this._mustWipeVertexAttributes) {
  16609. this._mustWipeVertexAttributes = false;
  16610. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16611. this._gl.disableVertexAttribArray(i);
  16612. this._vertexAttribArraysEnabled[i] = false;
  16613. this._currentBufferPointers[i].active = false;
  16614. }
  16615. return;
  16616. }
  16617. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16618. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16619. continue;
  16620. }
  16621. this._gl.disableVertexAttribArray(i);
  16622. this._vertexAttribArraysEnabled[i] = false;
  16623. this._currentBufferPointers[i].active = false;
  16624. }
  16625. };
  16626. /**
  16627. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16628. */
  16629. Engine.prototype.releaseEffects = function () {
  16630. for (var name in this._compiledEffects) {
  16631. this._deleteProgram(this._compiledEffects[name]._program);
  16632. }
  16633. this._compiledEffects = {};
  16634. };
  16635. /**
  16636. * Dispose and release all associated resources
  16637. */
  16638. Engine.prototype.dispose = function () {
  16639. this.hideLoadingUI();
  16640. this.stopRenderLoop();
  16641. // Release postProcesses
  16642. while (this.postProcesses.length) {
  16643. this.postProcesses[0].dispose();
  16644. }
  16645. // Empty texture
  16646. if (this._emptyTexture) {
  16647. this._releaseTexture(this._emptyTexture);
  16648. this._emptyTexture = null;
  16649. }
  16650. if (this._emptyCubeTexture) {
  16651. this._releaseTexture(this._emptyCubeTexture);
  16652. this._emptyCubeTexture = null;
  16653. }
  16654. // Rescale PP
  16655. if (this._rescalePostProcess) {
  16656. this._rescalePostProcess.dispose();
  16657. }
  16658. // Release scenes
  16659. while (this.scenes.length) {
  16660. this.scenes[0].dispose();
  16661. }
  16662. // Release audio engine
  16663. if (Engine.audioEngine) {
  16664. Engine.audioEngine.dispose();
  16665. }
  16666. // Release effects
  16667. this.releaseEffects();
  16668. // Unbind
  16669. this.unbindAllAttributes();
  16670. this._boundUniforms = [];
  16671. if (this._dummyFramebuffer) {
  16672. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16673. }
  16674. //WebVR
  16675. this.disableVR();
  16676. // Events
  16677. if (BABYLON.Tools.IsWindowObjectExist()) {
  16678. window.removeEventListener("blur", this._onBlur);
  16679. window.removeEventListener("focus", this._onFocus);
  16680. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16681. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16682. if (this._renderingCanvas) {
  16683. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16684. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16685. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16686. if (!this._doNotHandleContextLost) {
  16687. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16688. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16689. }
  16690. }
  16691. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16692. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16693. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16694. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16695. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16696. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16697. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16698. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16699. if (this._onVrDisplayConnect) {
  16700. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16701. if (this._onVrDisplayDisconnect) {
  16702. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16703. }
  16704. if (this._onVrDisplayPresentChange) {
  16705. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16706. }
  16707. this._onVrDisplayConnect = null;
  16708. this._onVrDisplayDisconnect = null;
  16709. }
  16710. }
  16711. // Remove from Instances
  16712. var index = Engine.Instances.indexOf(this);
  16713. if (index >= 0) {
  16714. Engine.Instances.splice(index, 1);
  16715. }
  16716. this._workingCanvas = null;
  16717. this._workingContext = null;
  16718. this._currentBufferPointers = [];
  16719. this._renderingCanvas = null;
  16720. this._currentProgram = null;
  16721. this._bindedRenderFunction = null;
  16722. this.onResizeObservable.clear();
  16723. this.onCanvasBlurObservable.clear();
  16724. this.onCanvasFocusObservable.clear();
  16725. this.onCanvasPointerOutObservable.clear();
  16726. this.onBeginFrameObservable.clear();
  16727. this.onEndFrameObservable.clear();
  16728. BABYLON.Effect.ResetCache();
  16729. // Abort active requests
  16730. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16731. var request = _a[_i];
  16732. request.abort();
  16733. }
  16734. };
  16735. // Loading screen
  16736. /**
  16737. * Display the loading screen
  16738. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16739. */
  16740. Engine.prototype.displayLoadingUI = function () {
  16741. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16742. return;
  16743. }
  16744. var loadingScreen = this.loadingScreen;
  16745. if (loadingScreen) {
  16746. loadingScreen.displayLoadingUI();
  16747. }
  16748. };
  16749. /**
  16750. * Hide the loading screen
  16751. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16752. */
  16753. Engine.prototype.hideLoadingUI = function () {
  16754. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16755. return;
  16756. }
  16757. var loadingScreen = this.loadingScreen;
  16758. if (loadingScreen) {
  16759. loadingScreen.hideLoadingUI();
  16760. }
  16761. };
  16762. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16763. /**
  16764. * Gets the current loading screen object
  16765. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16766. */
  16767. get: function () {
  16768. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16769. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16770. return this._loadingScreen;
  16771. },
  16772. /**
  16773. * Sets the current loading screen object
  16774. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16775. */
  16776. set: function (loadingScreen) {
  16777. this._loadingScreen = loadingScreen;
  16778. },
  16779. enumerable: true,
  16780. configurable: true
  16781. });
  16782. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16783. /**
  16784. * Sets the current loading screen text
  16785. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16786. */
  16787. set: function (text) {
  16788. this.loadingScreen.loadingUIText = text;
  16789. },
  16790. enumerable: true,
  16791. configurable: true
  16792. });
  16793. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16794. /**
  16795. * Sets the current loading screen background color
  16796. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16797. */
  16798. set: function (color) {
  16799. this.loadingScreen.loadingUIBackgroundColor = color;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. /**
  16805. * Attach a new callback raised when context lost event is fired
  16806. * @param callback defines the callback to call
  16807. */
  16808. Engine.prototype.attachContextLostEvent = function (callback) {
  16809. if (this._renderingCanvas) {
  16810. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16811. }
  16812. };
  16813. /**
  16814. * Attach a new callback raised when context restored event is fired
  16815. * @param callback defines the callback to call
  16816. */
  16817. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16818. if (this._renderingCanvas) {
  16819. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16820. }
  16821. };
  16822. /**
  16823. * Gets the source code of the vertex shader associated with a specific webGL program
  16824. * @param program defines the program to use
  16825. * @returns a string containing the source code of the vertex shader associated with the program
  16826. */
  16827. Engine.prototype.getVertexShaderSource = function (program) {
  16828. var shaders = this._gl.getAttachedShaders(program);
  16829. if (!shaders) {
  16830. return null;
  16831. }
  16832. return this._gl.getShaderSource(shaders[0]);
  16833. };
  16834. /**
  16835. * Gets the source code of the fragment shader associated with a specific webGL program
  16836. * @param program defines the program to use
  16837. * @returns a string containing the source code of the fragment shader associated with the program
  16838. */
  16839. Engine.prototype.getFragmentShaderSource = function (program) {
  16840. var shaders = this._gl.getAttachedShaders(program);
  16841. if (!shaders) {
  16842. return null;
  16843. }
  16844. return this._gl.getShaderSource(shaders[1]);
  16845. };
  16846. /**
  16847. * Get the current error code of the webGL context
  16848. * @returns the error code
  16849. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16850. */
  16851. Engine.prototype.getError = function () {
  16852. return this._gl.getError();
  16853. };
  16854. // FPS
  16855. /**
  16856. * Gets the current framerate
  16857. * @returns a number representing the framerate
  16858. */
  16859. Engine.prototype.getFps = function () {
  16860. return this._fps;
  16861. };
  16862. /**
  16863. * Gets the time spent between current and previous frame
  16864. * @returns a number representing the delta time in ms
  16865. */
  16866. Engine.prototype.getDeltaTime = function () {
  16867. return this._deltaTime;
  16868. };
  16869. Engine.prototype._measureFps = function () {
  16870. this._performanceMonitor.sampleFrame();
  16871. this._fps = this._performanceMonitor.averageFPS;
  16872. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16873. };
  16874. /** @hidden */
  16875. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16876. if (faceIndex === void 0) { faceIndex = -1; }
  16877. var gl = this._gl;
  16878. if (!this._dummyFramebuffer) {
  16879. var dummy = gl.createFramebuffer();
  16880. if (!dummy) {
  16881. throw new Error("Unable to create dummy framebuffer");
  16882. }
  16883. this._dummyFramebuffer = dummy;
  16884. }
  16885. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16886. if (faceIndex > -1) {
  16887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16888. }
  16889. else {
  16890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16891. }
  16892. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16893. var buffer;
  16894. switch (readType) {
  16895. case gl.UNSIGNED_BYTE:
  16896. buffer = new Uint8Array(4 * width * height);
  16897. readType = gl.UNSIGNED_BYTE;
  16898. break;
  16899. default:
  16900. buffer = new Float32Array(4 * width * height);
  16901. readType = gl.FLOAT;
  16902. break;
  16903. }
  16904. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16905. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16906. return buffer;
  16907. };
  16908. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16909. if (this._webGLVersion > 1) {
  16910. return this._caps.colorBufferFloat;
  16911. }
  16912. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16913. };
  16914. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16915. if (this._webGLVersion > 1) {
  16916. return this._caps.colorBufferFloat;
  16917. }
  16918. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16919. };
  16920. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16921. Engine.prototype._canRenderToFramebuffer = function (type) {
  16922. var gl = this._gl;
  16923. //clear existing errors
  16924. while (gl.getError() !== gl.NO_ERROR) { }
  16925. var successful = true;
  16926. var texture = gl.createTexture();
  16927. gl.bindTexture(gl.TEXTURE_2D, texture);
  16928. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16931. var fb = gl.createFramebuffer();
  16932. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16933. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16934. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16935. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16936. successful = successful && (gl.getError() === gl.NO_ERROR);
  16937. //try render by clearing frame buffer's color buffer
  16938. if (successful) {
  16939. gl.clear(gl.COLOR_BUFFER_BIT);
  16940. successful = successful && (gl.getError() === gl.NO_ERROR);
  16941. }
  16942. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16943. if (successful) {
  16944. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16945. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16946. var readFormat = gl.RGBA;
  16947. var readType = gl.UNSIGNED_BYTE;
  16948. var buffer = new Uint8Array(4);
  16949. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16950. successful = successful && (gl.getError() === gl.NO_ERROR);
  16951. }
  16952. //clean up
  16953. gl.deleteTexture(texture);
  16954. gl.deleteFramebuffer(fb);
  16955. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16956. //clear accumulated errors
  16957. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16958. return successful;
  16959. };
  16960. /** @hidden */
  16961. Engine.prototype._getWebGLTextureType = function (type) {
  16962. if (type === Engine.TEXTURETYPE_FLOAT) {
  16963. return this._gl.FLOAT;
  16964. }
  16965. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16966. // Add Half Float Constant.
  16967. return this._gl.HALF_FLOAT_OES;
  16968. }
  16969. return this._gl.UNSIGNED_BYTE;
  16970. };
  16971. ;
  16972. Engine.prototype._getInternalFormat = function (format) {
  16973. var internalFormat = this._gl.RGBA;
  16974. switch (format) {
  16975. case Engine.TEXTUREFORMAT_ALPHA:
  16976. internalFormat = this._gl.ALPHA;
  16977. break;
  16978. case Engine.TEXTUREFORMAT_LUMINANCE:
  16979. internalFormat = this._gl.LUMINANCE;
  16980. break;
  16981. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16982. internalFormat = this._gl.LUMINANCE_ALPHA;
  16983. break;
  16984. case Engine.TEXTUREFORMAT_RGB:
  16985. case Engine.TEXTUREFORMAT_RGB32F:
  16986. internalFormat = this._gl.RGB;
  16987. break;
  16988. case Engine.TEXTUREFORMAT_RGBA:
  16989. case Engine.TEXTUREFORMAT_RGBA32F:
  16990. internalFormat = this._gl.RGBA;
  16991. break;
  16992. case Engine.TEXTUREFORMAT_R32F:
  16993. internalFormat = this._gl.RED;
  16994. break;
  16995. case Engine.TEXTUREFORMAT_RG32F:
  16996. internalFormat = this._gl.RG;
  16997. break;
  16998. }
  16999. return internalFormat;
  17000. };
  17001. /** @hidden */
  17002. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17003. if (this._webGLVersion === 1) {
  17004. if (format) {
  17005. switch (format) {
  17006. case Engine.TEXTUREFORMAT_LUMINANCE:
  17007. return this._gl.LUMINANCE;
  17008. }
  17009. }
  17010. return this._gl.RGBA;
  17011. }
  17012. if (type === Engine.TEXTURETYPE_FLOAT) {
  17013. if (format) {
  17014. switch (format) {
  17015. case Engine.TEXTUREFORMAT_R32F:
  17016. return this._gl.R32F;
  17017. case Engine.TEXTUREFORMAT_RG32F:
  17018. return this._gl.RG32F;
  17019. case Engine.TEXTUREFORMAT_RGB32F:
  17020. return this._gl.RGB32F;
  17021. }
  17022. }
  17023. return this._gl.RGBA32F;
  17024. }
  17025. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17026. return this._gl.RGBA16F;
  17027. }
  17028. if (format) {
  17029. switch (format) {
  17030. case Engine.TEXTUREFORMAT_LUMINANCE:
  17031. return this._gl.LUMINANCE;
  17032. case Engine.TEXTUREFORMAT_RGB:
  17033. return this._gl.RGB;
  17034. }
  17035. }
  17036. return this._gl.RGBA;
  17037. };
  17038. ;
  17039. /** @hidden */
  17040. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17041. if (type === Engine.TEXTURETYPE_FLOAT) {
  17042. return this._gl.RGBA32F;
  17043. }
  17044. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17045. return this._gl.RGBA16F;
  17046. }
  17047. return this._gl.RGBA8;
  17048. };
  17049. ;
  17050. /**
  17051. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17052. * @return the new query
  17053. */
  17054. Engine.prototype.createQuery = function () {
  17055. return this._gl.createQuery();
  17056. };
  17057. /**
  17058. * Delete and release a webGL query
  17059. * @param query defines the query to delete
  17060. * @return the current engine
  17061. */
  17062. Engine.prototype.deleteQuery = function (query) {
  17063. this._gl.deleteQuery(query);
  17064. return this;
  17065. };
  17066. /**
  17067. * Check if a given query has resolved and got its value
  17068. * @param query defines the query to check
  17069. * @returns true if the query got its value
  17070. */
  17071. Engine.prototype.isQueryResultAvailable = function (query) {
  17072. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17073. };
  17074. /**
  17075. * Gets the value of a given query
  17076. * @param query defines the query to check
  17077. * @returns the value of the query
  17078. */
  17079. Engine.prototype.getQueryResult = function (query) {
  17080. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17081. };
  17082. /**
  17083. * Initiates an occlusion query
  17084. * @param algorithmType defines the algorithm to use
  17085. * @param query defines the query to use
  17086. * @returns the current engine
  17087. * @see http://doc.babylonjs.com/features/occlusionquery
  17088. */
  17089. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17090. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17091. this._gl.beginQuery(glAlgorithm, query);
  17092. return this;
  17093. };
  17094. /**
  17095. * Ends an occlusion query
  17096. * @see http://doc.babylonjs.com/features/occlusionquery
  17097. * @param algorithmType defines the algorithm to use
  17098. * @returns the current engine
  17099. */
  17100. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17101. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17102. this._gl.endQuery(glAlgorithm);
  17103. return this;
  17104. };
  17105. /* Time queries */
  17106. Engine.prototype._createTimeQuery = function () {
  17107. var timerQuery = this._caps.timerQuery;
  17108. if (timerQuery.createQueryEXT) {
  17109. return timerQuery.createQueryEXT();
  17110. }
  17111. return this.createQuery();
  17112. };
  17113. Engine.prototype._deleteTimeQuery = function (query) {
  17114. var timerQuery = this._caps.timerQuery;
  17115. if (timerQuery.deleteQueryEXT) {
  17116. timerQuery.deleteQueryEXT(query);
  17117. return;
  17118. }
  17119. this.deleteQuery(query);
  17120. };
  17121. Engine.prototype._getTimeQueryResult = function (query) {
  17122. var timerQuery = this._caps.timerQuery;
  17123. if (timerQuery.getQueryObjectEXT) {
  17124. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17125. }
  17126. return this.getQueryResult(query);
  17127. };
  17128. Engine.prototype._getTimeQueryAvailability = function (query) {
  17129. var timerQuery = this._caps.timerQuery;
  17130. if (timerQuery.getQueryObjectEXT) {
  17131. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17132. }
  17133. return this.isQueryResultAvailable(query);
  17134. };
  17135. /**
  17136. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17137. * Please note that only one query can be issued at a time
  17138. * @returns a time token used to track the time span
  17139. */
  17140. Engine.prototype.startTimeQuery = function () {
  17141. var timerQuery = this._caps.timerQuery;
  17142. if (!timerQuery) {
  17143. return null;
  17144. }
  17145. var token = new BABYLON._TimeToken();
  17146. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17147. if (this._caps.canUseTimestampForTimerQuery) {
  17148. token._startTimeQuery = this._createTimeQuery();
  17149. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17150. }
  17151. else {
  17152. if (this._currentNonTimestampToken) {
  17153. return this._currentNonTimestampToken;
  17154. }
  17155. token._timeElapsedQuery = this._createTimeQuery();
  17156. if (timerQuery.beginQueryEXT) {
  17157. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17158. }
  17159. else {
  17160. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17161. }
  17162. this._currentNonTimestampToken = token;
  17163. }
  17164. return token;
  17165. };
  17166. /**
  17167. * Ends a time query
  17168. * @param token defines the token used to measure the time span
  17169. * @returns the time spent (in ns)
  17170. */
  17171. Engine.prototype.endTimeQuery = function (token) {
  17172. var timerQuery = this._caps.timerQuery;
  17173. if (!timerQuery || !token) {
  17174. return -1;
  17175. }
  17176. if (this._caps.canUseTimestampForTimerQuery) {
  17177. if (!token._startTimeQuery) {
  17178. return -1;
  17179. }
  17180. if (!token._endTimeQuery) {
  17181. token._endTimeQuery = this._createTimeQuery();
  17182. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17183. }
  17184. }
  17185. else if (!token._timeElapsedQueryEnded) {
  17186. if (!token._timeElapsedQuery) {
  17187. return -1;
  17188. }
  17189. if (timerQuery.endQueryEXT) {
  17190. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17191. }
  17192. else {
  17193. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17194. }
  17195. token._timeElapsedQueryEnded = true;
  17196. }
  17197. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17198. var available = false;
  17199. if (token._endTimeQuery) {
  17200. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17201. }
  17202. else if (token._timeElapsedQuery) {
  17203. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17204. }
  17205. if (available && !disjoint) {
  17206. var result = 0;
  17207. if (this._caps.canUseTimestampForTimerQuery) {
  17208. if (!token._startTimeQuery || !token._endTimeQuery) {
  17209. return -1;
  17210. }
  17211. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17212. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17213. result = timeEnd - timeStart;
  17214. this._deleteTimeQuery(token._startTimeQuery);
  17215. this._deleteTimeQuery(token._endTimeQuery);
  17216. token._startTimeQuery = null;
  17217. token._endTimeQuery = null;
  17218. }
  17219. else {
  17220. if (!token._timeElapsedQuery) {
  17221. return -1;
  17222. }
  17223. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17224. this._deleteTimeQuery(token._timeElapsedQuery);
  17225. token._timeElapsedQuery = null;
  17226. token._timeElapsedQueryEnded = false;
  17227. this._currentNonTimestampToken = null;
  17228. }
  17229. return result;
  17230. }
  17231. return -1;
  17232. };
  17233. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17234. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17235. };
  17236. // Transform feedback
  17237. /**
  17238. * Creates a webGL transform feedback object
  17239. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17240. * @returns the webGL transform feedback object
  17241. */
  17242. Engine.prototype.createTransformFeedback = function () {
  17243. return this._gl.createTransformFeedback();
  17244. };
  17245. /**
  17246. * Delete a webGL transform feedback object
  17247. * @param value defines the webGL transform feedback object to delete
  17248. */
  17249. Engine.prototype.deleteTransformFeedback = function (value) {
  17250. this._gl.deleteTransformFeedback(value);
  17251. };
  17252. /**
  17253. * Bind a webGL transform feedback object to the webgl context
  17254. * @param value defines the webGL transform feedback object to bind
  17255. */
  17256. Engine.prototype.bindTransformFeedback = function (value) {
  17257. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17258. };
  17259. /**
  17260. * Begins a transform feedback operation
  17261. * @param usePoints defines if points or triangles must be used
  17262. */
  17263. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17264. if (usePoints === void 0) { usePoints = true; }
  17265. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17266. };
  17267. /**
  17268. * Ends a transform feedback operation
  17269. */
  17270. Engine.prototype.endTransformFeedback = function () {
  17271. this._gl.endTransformFeedback();
  17272. };
  17273. /**
  17274. * Specify the varyings to use with transform feedback
  17275. * @param program defines the associated webGL program
  17276. * @param value defines the list of strings representing the varying names
  17277. */
  17278. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17279. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17280. };
  17281. /**
  17282. * Bind a webGL buffer for a transform feedback operation
  17283. * @param value defines the webGL buffer to bind
  17284. */
  17285. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17286. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17287. };
  17288. /** @hidden */
  17289. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17290. var _this = this;
  17291. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17292. this._activeRequests.push(request);
  17293. request.onCompleteObservable.add(function (request) {
  17294. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17295. });
  17296. return request;
  17297. };
  17298. /** @hidden */
  17299. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17300. var _this = this;
  17301. return new Promise(function (resolve, reject) {
  17302. _this._loadFile(url, function (data) {
  17303. resolve(data);
  17304. }, undefined, database, useArrayBuffer, function (request, exception) {
  17305. reject(exception);
  17306. });
  17307. });
  17308. };
  17309. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17310. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17311. var onload = function (data) {
  17312. loadedFiles[index] = data;
  17313. loadedFiles._internalCount++;
  17314. if (loadedFiles._internalCount === 6) {
  17315. onfinish(loadedFiles);
  17316. }
  17317. };
  17318. var onerror = function (request, exception) {
  17319. if (onErrorCallBack && request) {
  17320. onErrorCallBack(request.status + " " + request.statusText, exception);
  17321. }
  17322. };
  17323. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17324. };
  17325. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17326. if (onError === void 0) { onError = null; }
  17327. var loadedFiles = [];
  17328. loadedFiles._internalCount = 0;
  17329. for (var index = 0; index < 6; index++) {
  17330. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17331. }
  17332. };
  17333. // Statics
  17334. /**
  17335. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17336. * @returns true if the engine can be created
  17337. * @ignorenaming
  17338. */
  17339. Engine.isSupported = function () {
  17340. try {
  17341. var tempcanvas = document.createElement("canvas");
  17342. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17343. return gl != null && !!window.WebGLRenderingContext;
  17344. }
  17345. catch (e) {
  17346. return false;
  17347. }
  17348. };
  17349. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17350. Engine.ExceptionList = [
  17351. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17352. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17353. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17354. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17355. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17356. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17357. ];
  17358. /** Gets the list of created engines */
  17359. Engine.Instances = new Array();
  17360. // Const statics
  17361. Engine._ALPHA_DISABLE = 0;
  17362. Engine._ALPHA_ADD = 1;
  17363. Engine._ALPHA_COMBINE = 2;
  17364. Engine._ALPHA_SUBTRACT = 3;
  17365. Engine._ALPHA_MULTIPLY = 4;
  17366. Engine._ALPHA_MAXIMIZED = 5;
  17367. Engine._ALPHA_ONEONE = 6;
  17368. Engine._ALPHA_PREMULTIPLIED = 7;
  17369. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17370. Engine._ALPHA_INTERPOLATE = 9;
  17371. Engine._ALPHA_SCREENMODE = 10;
  17372. Engine._DELAYLOADSTATE_NONE = 0;
  17373. Engine._DELAYLOADSTATE_LOADED = 1;
  17374. Engine._DELAYLOADSTATE_LOADING = 2;
  17375. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17376. Engine._TEXTUREFORMAT_ALPHA = 0;
  17377. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17378. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17379. Engine._TEXTUREFORMAT_RGB = 4;
  17380. Engine._TEXTUREFORMAT_RGBA = 5;
  17381. Engine._TEXTUREFORMAT_R32F = 6;
  17382. Engine._TEXTUREFORMAT_RG32F = 7;
  17383. Engine._TEXTUREFORMAT_RGB32F = 8;
  17384. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17385. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17386. Engine._TEXTURETYPE_FLOAT = 1;
  17387. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17388. // Depht or Stencil test Constants.
  17389. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17390. 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.
  17391. 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.
  17392. 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.
  17393. 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.
  17394. 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.
  17395. 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.
  17396. 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.
  17397. // Stencil Actions Constants.
  17398. Engine._KEEP = 0x1E00;
  17399. Engine._REPLACE = 0x1E01;
  17400. Engine._INCR = 0x1E02;
  17401. Engine._DECR = 0x1E03;
  17402. Engine._INVERT = 0x150A;
  17403. Engine._INCR_WRAP = 0x8507;
  17404. Engine._DECR_WRAP = 0x8508;
  17405. // Texture rescaling mode
  17406. Engine._SCALEMODE_FLOOR = 1;
  17407. Engine._SCALEMODE_NEAREST = 2;
  17408. Engine._SCALEMODE_CEILING = 3;
  17409. // Updatable statics so stick with vars here
  17410. /**
  17411. * Gets or sets the epsilon value used by collision engine
  17412. */
  17413. Engine.CollisionsEpsilon = 0.001;
  17414. /**
  17415. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17416. */
  17417. Engine.CodeRepository = "src/";
  17418. /**
  17419. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17420. */
  17421. Engine.ShadersRepository = "src/Shaders/";
  17422. return Engine;
  17423. }());
  17424. BABYLON.Engine = Engine;
  17425. })(BABYLON || (BABYLON = {}));
  17426. //# sourceMappingURL=babylon.engine.js.map
  17427. var BABYLON;
  17428. (function (BABYLON) {
  17429. /**
  17430. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17431. */
  17432. var Node = /** @class */ (function () {
  17433. /**
  17434. * Creates a new Node
  17435. * @param {string} name - the name and id to be given to this node
  17436. * @param {BABYLON.Scene} the scene this node will be added to
  17437. */
  17438. function Node(name, scene) {
  17439. if (scene === void 0) { scene = null; }
  17440. /**
  17441. * Gets or sets a string used to store user defined state for the node
  17442. */
  17443. this.state = "";
  17444. /**
  17445. * Gets or sets an object used to store user defined information for the node
  17446. */
  17447. this.metadata = null;
  17448. /**
  17449. * Gets or sets a boolean used to define if the node must be serialized
  17450. */
  17451. this.doNotSerialize = false;
  17452. /** @hidden */
  17453. this._isDisposed = false;
  17454. /**
  17455. * Gets a list of Animations associated with the node
  17456. */
  17457. this.animations = new Array();
  17458. this._ranges = {};
  17459. this._isEnabled = true;
  17460. this._isReady = true;
  17461. /** @hidden */
  17462. this._currentRenderId = -1;
  17463. this._parentRenderId = -1;
  17464. this._childRenderId = -1;
  17465. this._animationPropertiesOverride = null;
  17466. /**
  17467. * An event triggered when the mesh is disposed
  17468. */
  17469. this.onDisposeObservable = new BABYLON.Observable();
  17470. // Behaviors
  17471. this._behaviors = new Array();
  17472. this.name = name;
  17473. this.id = name;
  17474. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17475. this.uniqueId = this._scene.getUniqueId();
  17476. this._initCache();
  17477. }
  17478. /**
  17479. * Gets a boolean indicating if the node has been disposed
  17480. * @returns true if the node was disposed
  17481. */
  17482. Node.prototype.isDisposed = function () {
  17483. return this._isDisposed;
  17484. };
  17485. Object.defineProperty(Node.prototype, "parent", {
  17486. get: function () {
  17487. return this._parentNode;
  17488. },
  17489. /**
  17490. * Gets or sets the parent of the node
  17491. */
  17492. set: function (parent) {
  17493. if (this._parentNode === parent) {
  17494. return;
  17495. }
  17496. // Remove self from list of children of parent
  17497. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17498. var index = this._parentNode._children.indexOf(this);
  17499. if (index !== -1) {
  17500. this._parentNode._children.splice(index, 1);
  17501. }
  17502. }
  17503. // Store new parent
  17504. this._parentNode = parent;
  17505. // Add as child to new parent
  17506. if (this._parentNode) {
  17507. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17508. this._parentNode._children = new Array();
  17509. }
  17510. this._parentNode._children.push(this);
  17511. }
  17512. },
  17513. enumerable: true,
  17514. configurable: true
  17515. });
  17516. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17517. /**
  17518. * Gets or sets the animation properties override
  17519. */
  17520. get: function () {
  17521. if (!this._animationPropertiesOverride) {
  17522. return this._scene.animationPropertiesOverride;
  17523. }
  17524. return this._animationPropertiesOverride;
  17525. },
  17526. set: function (value) {
  17527. this._animationPropertiesOverride = value;
  17528. },
  17529. enumerable: true,
  17530. configurable: true
  17531. });
  17532. /**
  17533. * Gets a string idenfifying the name of the class
  17534. * @returns "Node" string
  17535. */
  17536. Node.prototype.getClassName = function () {
  17537. return "Node";
  17538. };
  17539. Object.defineProperty(Node.prototype, "onDispose", {
  17540. /**
  17541. * Sets a callback that will be raised when the node will be disposed
  17542. */
  17543. set: function (callback) {
  17544. if (this._onDisposeObserver) {
  17545. this.onDisposeObservable.remove(this._onDisposeObserver);
  17546. }
  17547. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. /**
  17553. * Gets the scene of the node
  17554. * @returns a {BABYLON.Scene}
  17555. */
  17556. Node.prototype.getScene = function () {
  17557. return this._scene;
  17558. };
  17559. /**
  17560. * Gets the engine of the node
  17561. * @returns a {BABYLON.Engine}
  17562. */
  17563. Node.prototype.getEngine = function () {
  17564. return this._scene.getEngine();
  17565. };
  17566. /**
  17567. * Attach a behavior to the node
  17568. * @see http://doc.babylonjs.com/features/behaviour
  17569. * @param behavior defines the behavior to attach
  17570. * @returns the current Node
  17571. */
  17572. Node.prototype.addBehavior = function (behavior) {
  17573. var _this = this;
  17574. var index = this._behaviors.indexOf(behavior);
  17575. if (index !== -1) {
  17576. return this;
  17577. }
  17578. behavior.init();
  17579. if (this._scene.isLoading) {
  17580. // We defer the attach when the scene will be loaded
  17581. var observer = this._scene.onDataLoadedObservable.add(function () {
  17582. behavior.attach(_this);
  17583. setTimeout(function () {
  17584. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17585. _this._scene.onDataLoadedObservable.remove(observer);
  17586. }, 0);
  17587. });
  17588. }
  17589. else {
  17590. behavior.attach(this);
  17591. }
  17592. this._behaviors.push(behavior);
  17593. return this;
  17594. };
  17595. /**
  17596. * Remove an attached behavior
  17597. * @see http://doc.babylonjs.com/features/behaviour
  17598. * @param behavior defines the behavior to attach
  17599. * @returns the current Node
  17600. */
  17601. Node.prototype.removeBehavior = function (behavior) {
  17602. var index = this._behaviors.indexOf(behavior);
  17603. if (index === -1) {
  17604. return this;
  17605. }
  17606. this._behaviors[index].detach();
  17607. this._behaviors.splice(index, 1);
  17608. return this;
  17609. };
  17610. Object.defineProperty(Node.prototype, "behaviors", {
  17611. /**
  17612. * Gets the list of attached behaviors
  17613. * @see http://doc.babylonjs.com/features/behaviour
  17614. */
  17615. get: function () {
  17616. return this._behaviors;
  17617. },
  17618. enumerable: true,
  17619. configurable: true
  17620. });
  17621. /**
  17622. * Gets an attached behavior by name
  17623. * @param name defines the name of the behavior to look for
  17624. * @see http://doc.babylonjs.com/features/behaviour
  17625. * @returns null if behavior was not found else the requested behavior
  17626. */
  17627. Node.prototype.getBehaviorByName = function (name) {
  17628. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17629. var behavior = _a[_i];
  17630. if (behavior.name === name) {
  17631. return behavior;
  17632. }
  17633. }
  17634. return null;
  17635. };
  17636. /**
  17637. * Returns the world matrix of the node
  17638. * @returns a matrix containing the node's world matrix
  17639. */
  17640. Node.prototype.getWorldMatrix = function () {
  17641. return BABYLON.Matrix.Identity();
  17642. };
  17643. /** @hidden */
  17644. Node.prototype._getWorldMatrixDeterminant = function () {
  17645. return 1;
  17646. };
  17647. // override it in derived class if you add new variables to the cache
  17648. // and call the parent class method
  17649. /** @hidden */
  17650. Node.prototype._initCache = function () {
  17651. this._cache = {};
  17652. this._cache.parent = undefined;
  17653. };
  17654. /** @hidden */
  17655. Node.prototype.updateCache = function (force) {
  17656. if (!force && this.isSynchronized())
  17657. return;
  17658. this._cache.parent = this.parent;
  17659. this._updateCache();
  17660. };
  17661. // override it in derived class if you add new variables to the cache
  17662. // and call the parent class method if !ignoreParentClass
  17663. /** @hidden */
  17664. Node.prototype._updateCache = function (ignoreParentClass) {
  17665. };
  17666. // override it in derived class if you add new variables to the cache
  17667. /** @hidden */
  17668. Node.prototype._isSynchronized = function () {
  17669. return true;
  17670. };
  17671. /** @hidden */
  17672. Node.prototype._markSyncedWithParent = function () {
  17673. if (this.parent) {
  17674. this._parentRenderId = this.parent._childRenderId;
  17675. }
  17676. };
  17677. /** @hidden */
  17678. Node.prototype.isSynchronizedWithParent = function () {
  17679. if (!this.parent) {
  17680. return true;
  17681. }
  17682. if (this._parentRenderId !== this.parent._childRenderId) {
  17683. return false;
  17684. }
  17685. return this.parent.isSynchronized();
  17686. };
  17687. /** @hidden */
  17688. Node.prototype.isSynchronized = function (updateCache) {
  17689. var check = this.hasNewParent();
  17690. check = check || !this.isSynchronizedWithParent();
  17691. check = check || !this._isSynchronized();
  17692. if (updateCache)
  17693. this.updateCache(true);
  17694. return !check;
  17695. };
  17696. /** @hidden */
  17697. Node.prototype.hasNewParent = function (update) {
  17698. if (this._cache.parent === this.parent)
  17699. return false;
  17700. if (update)
  17701. this._cache.parent = this.parent;
  17702. return true;
  17703. };
  17704. /**
  17705. * Is this node ready to be used/rendered
  17706. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17707. * @return true if the node is ready
  17708. */
  17709. Node.prototype.isReady = function (completeCheck) {
  17710. if (completeCheck === void 0) { completeCheck = false; }
  17711. return this._isReady;
  17712. };
  17713. /**
  17714. * Is this node enabled?
  17715. * 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
  17716. * @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
  17717. * @return whether this node (and its parent) is enabled
  17718. */
  17719. Node.prototype.isEnabled = function (checkAncestors) {
  17720. if (checkAncestors === void 0) { checkAncestors = true; }
  17721. if (checkAncestors === false) {
  17722. return this._isEnabled;
  17723. }
  17724. if (this._isEnabled === false) {
  17725. return false;
  17726. }
  17727. if (this.parent !== undefined && this.parent !== null) {
  17728. return this.parent.isEnabled(checkAncestors);
  17729. }
  17730. return true;
  17731. };
  17732. /**
  17733. * Set the enabled state of this node
  17734. * @param value defines the new enabled state
  17735. */
  17736. Node.prototype.setEnabled = function (value) {
  17737. this._isEnabled = value;
  17738. };
  17739. /**
  17740. * Is this node a descendant of the given node?
  17741. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17742. * @param ancestor defines the parent node to inspect
  17743. * @returns a boolean indicating if this node is a descendant of the given node
  17744. */
  17745. Node.prototype.isDescendantOf = function (ancestor) {
  17746. if (this.parent) {
  17747. if (this.parent === ancestor) {
  17748. return true;
  17749. }
  17750. return this.parent.isDescendantOf(ancestor);
  17751. }
  17752. return false;
  17753. };
  17754. /** @hidden */
  17755. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17756. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17757. if (!this._children) {
  17758. return;
  17759. }
  17760. for (var index = 0; index < this._children.length; index++) {
  17761. var item = this._children[index];
  17762. if (!predicate || predicate(item)) {
  17763. results.push(item);
  17764. }
  17765. if (!directDescendantsOnly) {
  17766. item._getDescendants(results, false, predicate);
  17767. }
  17768. }
  17769. };
  17770. /**
  17771. * Will return all nodes that have this node as ascendant
  17772. * @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
  17773. * @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
  17774. * @return all children nodes of all types
  17775. */
  17776. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17777. var results = new Array();
  17778. this._getDescendants(results, directDescendantsOnly, predicate);
  17779. return results;
  17780. };
  17781. /**
  17782. * Get all child-meshes of this node
  17783. * @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
  17784. * @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
  17785. * @returns an array of {BABYLON.AbstractMesh}
  17786. */
  17787. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17788. var results = [];
  17789. this._getDescendants(results, directDescendantsOnly, function (node) {
  17790. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17791. });
  17792. return results;
  17793. };
  17794. /**
  17795. * Get all child-transformNodes of this node
  17796. * @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
  17797. * @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
  17798. * @returns an array of {BABYLON.TransformNode}
  17799. */
  17800. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17801. var results = [];
  17802. this._getDescendants(results, directDescendantsOnly, function (node) {
  17803. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17804. });
  17805. return results;
  17806. };
  17807. /**
  17808. * Get all direct children of this node
  17809. * @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
  17810. * @returns an array of {BABYLON.Node}
  17811. */
  17812. Node.prototype.getChildren = function (predicate) {
  17813. return this.getDescendants(true, predicate);
  17814. };
  17815. /** @hidden */
  17816. Node.prototype._setReady = function (state) {
  17817. if (state === this._isReady) {
  17818. return;
  17819. }
  17820. if (!state) {
  17821. this._isReady = false;
  17822. return;
  17823. }
  17824. if (this.onReady) {
  17825. this.onReady(this);
  17826. }
  17827. this._isReady = true;
  17828. };
  17829. /**
  17830. * Get an animation by name
  17831. * @param name defines the name of the animation to look for
  17832. * @returns null if not found else the requested animation
  17833. */
  17834. Node.prototype.getAnimationByName = function (name) {
  17835. for (var i = 0; i < this.animations.length; i++) {
  17836. var animation = this.animations[i];
  17837. if (animation.name === name) {
  17838. return animation;
  17839. }
  17840. }
  17841. return null;
  17842. };
  17843. /**
  17844. * Creates an animation range for this node
  17845. * @param name defines the name of the range
  17846. * @param from defines the starting key
  17847. * @param to defines the end key
  17848. */
  17849. Node.prototype.createAnimationRange = function (name, from, to) {
  17850. // check name not already in use
  17851. if (!this._ranges[name]) {
  17852. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17853. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17854. if (this.animations[i]) {
  17855. this.animations[i].createRange(name, from, to);
  17856. }
  17857. }
  17858. }
  17859. };
  17860. /**
  17861. * Delete a specific animation range
  17862. * @param name defines the name of the range to delete
  17863. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17864. */
  17865. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17866. if (deleteFrames === void 0) { deleteFrames = true; }
  17867. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17868. if (this.animations[i]) {
  17869. this.animations[i].deleteRange(name, deleteFrames);
  17870. }
  17871. }
  17872. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17873. };
  17874. /**
  17875. * Get an animation range by name
  17876. * @param name defines the name of the animation range to look for
  17877. * @returns null if not found else the requested animation range
  17878. */
  17879. Node.prototype.getAnimationRange = function (name) {
  17880. return this._ranges[name];
  17881. };
  17882. /**
  17883. * Will start the animation sequence
  17884. * @param name defines the range frames for animation sequence
  17885. * @param loop defines if the animation should loop (false by default)
  17886. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17887. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17888. * @returns the object created for this animation. If range does not exist, it will return null
  17889. */
  17890. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17891. var range = this.getAnimationRange(name);
  17892. if (!range) {
  17893. return null;
  17894. }
  17895. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17896. };
  17897. /**
  17898. * Serialize animation ranges into a JSON compatible object
  17899. * @returns serialization object
  17900. */
  17901. Node.prototype.serializeAnimationRanges = function () {
  17902. var serializationRanges = [];
  17903. for (var name in this._ranges) {
  17904. var localRange = this._ranges[name];
  17905. if (!localRange) {
  17906. continue;
  17907. }
  17908. var range = {};
  17909. range.name = name;
  17910. range.from = localRange.from;
  17911. range.to = localRange.to;
  17912. serializationRanges.push(range);
  17913. }
  17914. return serializationRanges;
  17915. };
  17916. /**
  17917. * Computes the world matrix of the node
  17918. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17919. * @returns the world matrix
  17920. */
  17921. Node.prototype.computeWorldMatrix = function (force) {
  17922. return BABYLON.Matrix.Identity();
  17923. };
  17924. /**
  17925. * Releases resources associated with this node.
  17926. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17927. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17928. */
  17929. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17930. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17931. if (!doNotRecurse) {
  17932. var nodes = this.getDescendants(true);
  17933. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17934. var node = nodes_1[_i];
  17935. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17936. }
  17937. }
  17938. else {
  17939. var transformNodes = this.getChildTransformNodes(true);
  17940. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17941. var transformNode = transformNodes_1[_a];
  17942. transformNode.parent = null;
  17943. transformNode.computeWorldMatrix(true);
  17944. }
  17945. }
  17946. this.parent = null;
  17947. // Callback
  17948. this.onDisposeObservable.notifyObservers(this);
  17949. this.onDisposeObservable.clear();
  17950. // Behaviors
  17951. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17952. var behavior = _c[_b];
  17953. behavior.detach();
  17954. }
  17955. this._behaviors = [];
  17956. this._isDisposed = true;
  17957. };
  17958. /**
  17959. * Parse animation range data from a serialization object and store them into a given node
  17960. * @param node defines where to store the animation ranges
  17961. * @param parsedNode defines the serialization object to read data from
  17962. * @param scene defines the hosting scene
  17963. */
  17964. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17965. if (parsedNode.ranges) {
  17966. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17967. var data = parsedNode.ranges[index];
  17968. node.createAnimationRange(data.name, data.from, data.to);
  17969. }
  17970. }
  17971. };
  17972. __decorate([
  17973. BABYLON.serialize()
  17974. ], Node.prototype, "name", void 0);
  17975. __decorate([
  17976. BABYLON.serialize()
  17977. ], Node.prototype, "id", void 0);
  17978. __decorate([
  17979. BABYLON.serialize()
  17980. ], Node.prototype, "uniqueId", void 0);
  17981. __decorate([
  17982. BABYLON.serialize()
  17983. ], Node.prototype, "state", void 0);
  17984. __decorate([
  17985. BABYLON.serialize()
  17986. ], Node.prototype, "metadata", void 0);
  17987. return Node;
  17988. }());
  17989. BABYLON.Node = Node;
  17990. })(BABYLON || (BABYLON = {}));
  17991. //# sourceMappingURL=babylon.node.js.map
  17992. var BABYLON;
  17993. (function (BABYLON) {
  17994. var BoundingSphere = /** @class */ (function () {
  17995. /**
  17996. * Creates a new bounding sphere
  17997. * @param min defines the minimum vector (in local space)
  17998. * @param max defines the maximum vector (in local space)
  17999. */
  18000. function BoundingSphere(min, max) {
  18001. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18002. this.reConstruct(min, max);
  18003. }
  18004. /**
  18005. * Recreates the entire bounding sphere from scratch
  18006. * @param min defines the new minimum vector (in local space)
  18007. * @param max defines the new maximum vector (in local space)
  18008. */
  18009. BoundingSphere.prototype.reConstruct = function (min, max) {
  18010. this.minimum = min.clone();
  18011. this.maximum = max.clone();
  18012. var distance = BABYLON.Vector3.Distance(min, max);
  18013. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18014. this.radius = distance * 0.5;
  18015. this.centerWorld = BABYLON.Vector3.Zero();
  18016. this._update(BABYLON.Matrix.Identity());
  18017. };
  18018. // Methods
  18019. BoundingSphere.prototype._update = function (world) {
  18020. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18021. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18022. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18023. };
  18024. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18025. for (var i = 0; i < 6; i++) {
  18026. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18027. return false;
  18028. }
  18029. return true;
  18030. };
  18031. BoundingSphere.prototype.intersectsPoint = function (point) {
  18032. var x = this.centerWorld.x - point.x;
  18033. var y = this.centerWorld.y - point.y;
  18034. var z = this.centerWorld.z - point.z;
  18035. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18036. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18037. return false;
  18038. return true;
  18039. };
  18040. // Statics
  18041. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18042. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18043. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18044. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18045. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18046. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18047. return false;
  18048. return true;
  18049. };
  18050. return BoundingSphere;
  18051. }());
  18052. BABYLON.BoundingSphere = BoundingSphere;
  18053. })(BABYLON || (BABYLON = {}));
  18054. //# sourceMappingURL=babylon.boundingSphere.js.map
  18055. var BABYLON;
  18056. (function (BABYLON) {
  18057. var BoundingBox = /** @class */ (function () {
  18058. /**
  18059. * Creates a new bounding box
  18060. * @param min defines the minimum vector (in local space)
  18061. * @param max defines the maximum vector (in local space)
  18062. */
  18063. function BoundingBox(min, max) {
  18064. this.vectorsWorld = new Array();
  18065. this.reConstruct(min, max);
  18066. }
  18067. // Methods
  18068. /**
  18069. * Recreates the entire bounding box from scratch
  18070. * @param min defines the new minimum vector (in local space)
  18071. * @param max defines the new maximum vector (in local space)
  18072. */
  18073. BoundingBox.prototype.reConstruct = function (min, max) {
  18074. this.minimum = min.clone();
  18075. this.maximum = max.clone();
  18076. // Bounding vectors
  18077. this.vectors = new Array();
  18078. this.vectors.push(this.minimum.clone());
  18079. this.vectors.push(this.maximum.clone());
  18080. this.vectors.push(this.minimum.clone());
  18081. this.vectors[2].x = this.maximum.x;
  18082. this.vectors.push(this.minimum.clone());
  18083. this.vectors[3].y = this.maximum.y;
  18084. this.vectors.push(this.minimum.clone());
  18085. this.vectors[4].z = this.maximum.z;
  18086. this.vectors.push(this.maximum.clone());
  18087. this.vectors[5].z = this.minimum.z;
  18088. this.vectors.push(this.maximum.clone());
  18089. this.vectors[6].x = this.minimum.x;
  18090. this.vectors.push(this.maximum.clone());
  18091. this.vectors[7].y = this.minimum.y;
  18092. // OBB
  18093. this.center = this.maximum.add(this.minimum).scale(0.5);
  18094. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18095. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18096. // World
  18097. for (var index = 0; index < this.vectors.length; index++) {
  18098. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18099. }
  18100. this.minimumWorld = BABYLON.Vector3.Zero();
  18101. this.maximumWorld = BABYLON.Vector3.Zero();
  18102. this.centerWorld = BABYLON.Vector3.Zero();
  18103. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18104. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18105. };
  18106. BoundingBox.prototype.getWorldMatrix = function () {
  18107. return this._worldMatrix;
  18108. };
  18109. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18110. this._worldMatrix.copyFrom(matrix);
  18111. return this;
  18112. };
  18113. BoundingBox.prototype._update = function (world) {
  18114. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18115. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18116. for (var index = 0; index < this.vectors.length; index++) {
  18117. var v = this.vectorsWorld[index];
  18118. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18119. if (v.x < this.minimumWorld.x)
  18120. this.minimumWorld.x = v.x;
  18121. if (v.y < this.minimumWorld.y)
  18122. this.minimumWorld.y = v.y;
  18123. if (v.z < this.minimumWorld.z)
  18124. this.minimumWorld.z = v.z;
  18125. if (v.x > this.maximumWorld.x)
  18126. this.maximumWorld.x = v.x;
  18127. if (v.y > this.maximumWorld.y)
  18128. this.maximumWorld.y = v.y;
  18129. if (v.z > this.maximumWorld.z)
  18130. this.maximumWorld.z = v.z;
  18131. }
  18132. // Extend
  18133. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18134. this.extendSizeWorld.scaleInPlace(0.5);
  18135. // OBB
  18136. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18137. this.centerWorld.scaleInPlace(0.5);
  18138. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18139. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18140. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18141. this._worldMatrix = world;
  18142. };
  18143. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18144. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18145. };
  18146. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18147. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18148. };
  18149. BoundingBox.prototype.intersectsPoint = function (point) {
  18150. var delta = -BABYLON.Epsilon;
  18151. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18152. return false;
  18153. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18154. return false;
  18155. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18156. return false;
  18157. return true;
  18158. };
  18159. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18160. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18161. };
  18162. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18163. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18164. return false;
  18165. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18166. return false;
  18167. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18168. return false;
  18169. return true;
  18170. };
  18171. // Statics
  18172. BoundingBox.Intersects = function (box0, box1) {
  18173. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18174. return false;
  18175. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18176. return false;
  18177. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18178. return false;
  18179. return true;
  18180. };
  18181. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18182. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18183. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18184. return (num <= (sphereRadius * sphereRadius));
  18185. };
  18186. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18187. for (var p = 0; p < 6; p++) {
  18188. for (var i = 0; i < 8; i++) {
  18189. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18190. return false;
  18191. }
  18192. }
  18193. }
  18194. return true;
  18195. };
  18196. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18197. for (var p = 0; p < 6; p++) {
  18198. var inCount = 8;
  18199. for (var i = 0; i < 8; i++) {
  18200. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18201. --inCount;
  18202. }
  18203. else {
  18204. break;
  18205. }
  18206. }
  18207. if (inCount === 0)
  18208. return false;
  18209. }
  18210. return true;
  18211. };
  18212. return BoundingBox;
  18213. }());
  18214. BABYLON.BoundingBox = BoundingBox;
  18215. })(BABYLON || (BABYLON = {}));
  18216. //# sourceMappingURL=babylon.boundingBox.js.map
  18217. var BABYLON;
  18218. (function (BABYLON) {
  18219. var computeBoxExtents = function (axis, box) {
  18220. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18221. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18222. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18223. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18224. var r = r0 + r1 + r2;
  18225. return {
  18226. min: p - r,
  18227. max: p + r
  18228. };
  18229. };
  18230. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18231. var axisOverlap = function (axis, box0, box1) {
  18232. var result0 = computeBoxExtents(axis, box0);
  18233. var result1 = computeBoxExtents(axis, box1);
  18234. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18235. };
  18236. var BoundingInfo = /** @class */ (function () {
  18237. function BoundingInfo(minimum, maximum) {
  18238. this.minimum = minimum;
  18239. this.maximum = maximum;
  18240. this._isLocked = false;
  18241. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18242. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18243. }
  18244. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18245. get: function () {
  18246. return this._isLocked;
  18247. },
  18248. set: function (value) {
  18249. this._isLocked = value;
  18250. },
  18251. enumerable: true,
  18252. configurable: true
  18253. });
  18254. // Methods
  18255. BoundingInfo.prototype.update = function (world) {
  18256. if (this._isLocked) {
  18257. return;
  18258. }
  18259. this.boundingBox._update(world);
  18260. this.boundingSphere._update(world);
  18261. };
  18262. /**
  18263. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18264. * @param center New center of the bounding info
  18265. * @param extend New extend of the bounding info
  18266. */
  18267. BoundingInfo.prototype.centerOn = function (center, extend) {
  18268. this.minimum = center.subtract(extend);
  18269. this.maximum = center.add(extend);
  18270. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18271. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18272. return this;
  18273. };
  18274. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18275. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18276. return false;
  18277. return this.boundingBox.isInFrustum(frustumPlanes);
  18278. };
  18279. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18280. /**
  18281. * Gets the world distance between the min and max points of the bounding box
  18282. */
  18283. get: function () {
  18284. var boundingBox = this.boundingBox;
  18285. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18286. return size.length();
  18287. },
  18288. enumerable: true,
  18289. configurable: true
  18290. });
  18291. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18292. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18293. };
  18294. BoundingInfo.prototype._checkCollision = function (collider) {
  18295. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18296. };
  18297. BoundingInfo.prototype.intersectsPoint = function (point) {
  18298. if (!this.boundingSphere.centerWorld) {
  18299. return false;
  18300. }
  18301. if (!this.boundingSphere.intersectsPoint(point)) {
  18302. return false;
  18303. }
  18304. if (!this.boundingBox.intersectsPoint(point)) {
  18305. return false;
  18306. }
  18307. return true;
  18308. };
  18309. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18310. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18311. return false;
  18312. }
  18313. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18314. return false;
  18315. }
  18316. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18317. return false;
  18318. }
  18319. if (!precise) {
  18320. return true;
  18321. }
  18322. var box0 = this.boundingBox;
  18323. var box1 = boundingInfo.boundingBox;
  18324. if (!axisOverlap(box0.directions[0], box0, box1))
  18325. return false;
  18326. if (!axisOverlap(box0.directions[1], box0, box1))
  18327. return false;
  18328. if (!axisOverlap(box0.directions[2], box0, box1))
  18329. return false;
  18330. if (!axisOverlap(box1.directions[0], box0, box1))
  18331. return false;
  18332. if (!axisOverlap(box1.directions[1], box0, box1))
  18333. return false;
  18334. if (!axisOverlap(box1.directions[2], box0, box1))
  18335. return false;
  18336. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18337. return false;
  18338. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18339. return false;
  18340. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18341. return false;
  18342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18343. return false;
  18344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18345. return false;
  18346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18347. return false;
  18348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18349. return false;
  18350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18351. return false;
  18352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18353. return false;
  18354. return true;
  18355. };
  18356. return BoundingInfo;
  18357. }());
  18358. BABYLON.BoundingInfo = BoundingInfo;
  18359. })(BABYLON || (BABYLON = {}));
  18360. //# sourceMappingURL=babylon.boundingInfo.js.map
  18361. var BABYLON;
  18362. (function (BABYLON) {
  18363. var TransformNode = /** @class */ (function (_super) {
  18364. __extends(TransformNode, _super);
  18365. function TransformNode(name, scene, isPure) {
  18366. if (scene === void 0) { scene = null; }
  18367. if (isPure === void 0) { isPure = true; }
  18368. var _this = _super.call(this, name, scene) || this;
  18369. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18370. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18371. _this._up = new BABYLON.Vector3(0, 1, 0);
  18372. _this._right = new BABYLON.Vector3(1, 0, 0);
  18373. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18374. // Properties
  18375. _this._rotation = BABYLON.Vector3.Zero();
  18376. _this._scaling = BABYLON.Vector3.One();
  18377. _this._isDirty = false;
  18378. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18379. _this.scalingDeterminant = 1;
  18380. _this.infiniteDistance = false;
  18381. _this.position = BABYLON.Vector3.Zero();
  18382. _this._localWorld = BABYLON.Matrix.Zero();
  18383. _this._worldMatrix = BABYLON.Matrix.Zero();
  18384. _this._worldMatrixDeterminant = 0;
  18385. _this._absolutePosition = BABYLON.Vector3.Zero();
  18386. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18387. _this._postMultiplyPivotMatrix = false;
  18388. _this._isWorldMatrixFrozen = false;
  18389. /**
  18390. * An event triggered after the world matrix is updated
  18391. */
  18392. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18393. _this._nonUniformScaling = false;
  18394. if (isPure) {
  18395. _this.getScene().addTransformNode(_this);
  18396. }
  18397. return _this;
  18398. }
  18399. /**
  18400. * Gets a string idenfifying the name of the class
  18401. * @returns "TransformNode" string
  18402. */
  18403. TransformNode.prototype.getClassName = function () {
  18404. return "TransformNode";
  18405. };
  18406. Object.defineProperty(TransformNode.prototype, "rotation", {
  18407. /**
  18408. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18409. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18410. * Default : (0.0, 0.0, 0.0)
  18411. */
  18412. get: function () {
  18413. return this._rotation;
  18414. },
  18415. set: function (newRotation) {
  18416. this._rotation = newRotation;
  18417. },
  18418. enumerable: true,
  18419. configurable: true
  18420. });
  18421. Object.defineProperty(TransformNode.prototype, "scaling", {
  18422. /**
  18423. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18424. * Default : (1.0, 1.0, 1.0)
  18425. */
  18426. get: function () {
  18427. return this._scaling;
  18428. },
  18429. /**
  18430. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18431. * Default : (1.0, 1.0, 1.0)
  18432. */
  18433. set: function (newScaling) {
  18434. this._scaling = newScaling;
  18435. },
  18436. enumerable: true,
  18437. configurable: true
  18438. });
  18439. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18440. /**
  18441. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18442. * It's null by default.
  18443. * 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)
  18444. */
  18445. get: function () {
  18446. return this._rotationQuaternion;
  18447. },
  18448. set: function (quaternion) {
  18449. this._rotationQuaternion = quaternion;
  18450. //reset the rotation vector.
  18451. if (quaternion && this.rotation.length()) {
  18452. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18453. }
  18454. },
  18455. enumerable: true,
  18456. configurable: true
  18457. });
  18458. Object.defineProperty(TransformNode.prototype, "forward", {
  18459. /**
  18460. * The forward direction of that transform in world space.
  18461. */
  18462. get: function () {
  18463. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Object.defineProperty(TransformNode.prototype, "up", {
  18469. /**
  18470. * The up direction of that transform in world space.
  18471. */
  18472. get: function () {
  18473. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. Object.defineProperty(TransformNode.prototype, "right", {
  18479. /**
  18480. * The right direction of that transform in world space.
  18481. */
  18482. get: function () {
  18483. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. /**
  18489. * Returns the latest update of the World matrix
  18490. * Returns a Matrix.
  18491. */
  18492. TransformNode.prototype.getWorldMatrix = function () {
  18493. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18494. this.computeWorldMatrix();
  18495. }
  18496. return this._worldMatrix;
  18497. };
  18498. /** @hidden */
  18499. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18500. return this._worldMatrixDeterminant;
  18501. };
  18502. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18503. /**
  18504. * Returns directly the latest state of the mesh World matrix.
  18505. * A Matrix is returned.
  18506. */
  18507. get: function () {
  18508. return this._worldMatrix;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. /**
  18514. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18515. * Returns the TransformNode.
  18516. */
  18517. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18518. this._poseMatrix.copyFrom(matrix);
  18519. return this;
  18520. };
  18521. /**
  18522. * Returns the mesh Pose matrix.
  18523. * Returned object : Matrix
  18524. */
  18525. TransformNode.prototype.getPoseMatrix = function () {
  18526. return this._poseMatrix;
  18527. };
  18528. TransformNode.prototype._isSynchronized = function () {
  18529. if (this._isDirty) {
  18530. return false;
  18531. }
  18532. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18533. return false;
  18534. if (this._cache.pivotMatrixUpdated) {
  18535. return false;
  18536. }
  18537. if (this.infiniteDistance) {
  18538. return false;
  18539. }
  18540. if (!this._cache.position.equals(this.position))
  18541. return false;
  18542. if (this.rotationQuaternion) {
  18543. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18544. return false;
  18545. }
  18546. if (!this._cache.rotation.equals(this.rotation))
  18547. return false;
  18548. if (!this._cache.scaling.equals(this.scaling))
  18549. return false;
  18550. return true;
  18551. };
  18552. TransformNode.prototype._initCache = function () {
  18553. _super.prototype._initCache.call(this);
  18554. this._cache.localMatrixUpdated = false;
  18555. this._cache.position = BABYLON.Vector3.Zero();
  18556. this._cache.scaling = BABYLON.Vector3.Zero();
  18557. this._cache.rotation = BABYLON.Vector3.Zero();
  18558. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18559. this._cache.billboardMode = -1;
  18560. };
  18561. TransformNode.prototype.markAsDirty = function (property) {
  18562. if (property === "rotation") {
  18563. this.rotationQuaternion = null;
  18564. }
  18565. this._currentRenderId = Number.MAX_VALUE;
  18566. this._isDirty = true;
  18567. return this;
  18568. };
  18569. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18570. /**
  18571. * Returns the current mesh absolute position.
  18572. * Retuns a Vector3.
  18573. */
  18574. get: function () {
  18575. return this._absolutePosition;
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. /**
  18581. * Sets a new matrix to apply before all other transformation
  18582. * @param matrix defines the transform matrix
  18583. * @returns the current TransformNode
  18584. */
  18585. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18586. return this.setPivotMatrix(matrix, false);
  18587. };
  18588. /**
  18589. * Sets a new pivot matrix to the current node
  18590. * @param matrix defines the new pivot matrix to use
  18591. * @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
  18592. * @returns the current TransformNode
  18593. */
  18594. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18595. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18596. this._pivotMatrix = matrix.clone();
  18597. this._cache.pivotMatrixUpdated = true;
  18598. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18599. if (this._postMultiplyPivotMatrix) {
  18600. if (!this._pivotMatrixInverse) {
  18601. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18602. }
  18603. else {
  18604. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18605. }
  18606. }
  18607. return this;
  18608. };
  18609. /**
  18610. * Returns the mesh pivot matrix.
  18611. * Default : Identity.
  18612. * A Matrix is returned.
  18613. */
  18614. TransformNode.prototype.getPivotMatrix = function () {
  18615. return this._pivotMatrix;
  18616. };
  18617. /**
  18618. * Prevents the World matrix to be computed any longer.
  18619. * Returns the TransformNode.
  18620. */
  18621. TransformNode.prototype.freezeWorldMatrix = function () {
  18622. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18623. this.computeWorldMatrix(true);
  18624. this._isWorldMatrixFrozen = true;
  18625. return this;
  18626. };
  18627. /**
  18628. * Allows back the World matrix computation.
  18629. * Returns the TransformNode.
  18630. */
  18631. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18632. this._isWorldMatrixFrozen = false;
  18633. this.computeWorldMatrix(true);
  18634. return this;
  18635. };
  18636. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18637. /**
  18638. * True if the World matrix has been frozen.
  18639. * Returns a boolean.
  18640. */
  18641. get: function () {
  18642. return this._isWorldMatrixFrozen;
  18643. },
  18644. enumerable: true,
  18645. configurable: true
  18646. });
  18647. /**
  18648. * Retuns the mesh absolute position in the World.
  18649. * Returns a Vector3.
  18650. */
  18651. TransformNode.prototype.getAbsolutePosition = function () {
  18652. this.computeWorldMatrix();
  18653. return this._absolutePosition;
  18654. };
  18655. /**
  18656. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18657. * Returns the TransformNode.
  18658. */
  18659. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18660. if (!absolutePosition) {
  18661. return this;
  18662. }
  18663. var absolutePositionX;
  18664. var absolutePositionY;
  18665. var absolutePositionZ;
  18666. if (absolutePosition.x === undefined) {
  18667. if (arguments.length < 3) {
  18668. return this;
  18669. }
  18670. absolutePositionX = arguments[0];
  18671. absolutePositionY = arguments[1];
  18672. absolutePositionZ = arguments[2];
  18673. }
  18674. else {
  18675. absolutePositionX = absolutePosition.x;
  18676. absolutePositionY = absolutePosition.y;
  18677. absolutePositionZ = absolutePosition.z;
  18678. }
  18679. if (this.parent) {
  18680. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18681. invertParentWorldMatrix.invert();
  18682. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18683. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18684. }
  18685. else {
  18686. this.position.x = absolutePositionX;
  18687. this.position.y = absolutePositionY;
  18688. this.position.z = absolutePositionZ;
  18689. }
  18690. return this;
  18691. };
  18692. /**
  18693. * Sets the mesh position in its local space.
  18694. * Returns the TransformNode.
  18695. */
  18696. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18697. this.computeWorldMatrix();
  18698. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18699. return this;
  18700. };
  18701. /**
  18702. * Returns the mesh position in the local space from the current World matrix values.
  18703. * Returns a new Vector3.
  18704. */
  18705. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18706. this.computeWorldMatrix();
  18707. var invLocalWorldMatrix = this._localWorld.clone();
  18708. invLocalWorldMatrix.invert();
  18709. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18710. };
  18711. /**
  18712. * Translates the mesh along the passed Vector3 in its local space.
  18713. * Returns the TransformNode.
  18714. */
  18715. TransformNode.prototype.locallyTranslate = function (vector3) {
  18716. this.computeWorldMatrix(true);
  18717. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18718. return this;
  18719. };
  18720. /**
  18721. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18722. * @param targetPoint the position (must be in same space as current mesh) to look at
  18723. * @param yawCor optional yaw (y-axis) correction in radians
  18724. * @param pitchCor optional pitch (x-axis) correction in radians
  18725. * @param rollCor optional roll (z-axis) correction in radians
  18726. * @param space the choosen space of the target
  18727. * @returns the TransformNode.
  18728. */
  18729. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18730. if (yawCor === void 0) { yawCor = 0; }
  18731. if (pitchCor === void 0) { pitchCor = 0; }
  18732. if (rollCor === void 0) { rollCor = 0; }
  18733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18734. var dv = TransformNode._lookAtVectorCache;
  18735. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18736. targetPoint.subtractToRef(pos, dv);
  18737. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18738. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18739. var pitch = Math.atan2(dv.y, len);
  18740. if (this.rotationQuaternion) {
  18741. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18742. }
  18743. else {
  18744. this.rotation.x = pitch + pitchCor;
  18745. this.rotation.y = yaw + yawCor;
  18746. this.rotation.z = rollCor;
  18747. }
  18748. return this;
  18749. };
  18750. /**
  18751. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18752. * This Vector3 is expressed in the World space.
  18753. */
  18754. TransformNode.prototype.getDirection = function (localAxis) {
  18755. var result = BABYLON.Vector3.Zero();
  18756. this.getDirectionToRef(localAxis, result);
  18757. return result;
  18758. };
  18759. /**
  18760. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18761. * localAxis is expressed in the mesh local space.
  18762. * result is computed in the Wordl space from the mesh World matrix.
  18763. * Returns the TransformNode.
  18764. */
  18765. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18766. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18767. return this;
  18768. };
  18769. /**
  18770. * Sets a new pivot point to the current node
  18771. * @param point defines the new pivot point to use
  18772. * @param space defines if the point is in world or local space (local by default)
  18773. * @returns the current TransformNode
  18774. */
  18775. TransformNode.prototype.setPivotPoint = function (point, space) {
  18776. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18777. if (this.getScene().getRenderId() == 0) {
  18778. this.computeWorldMatrix(true);
  18779. }
  18780. var wm = this.getWorldMatrix();
  18781. if (space == BABYLON.Space.WORLD) {
  18782. var tmat = BABYLON.Tmp.Matrix[0];
  18783. wm.invertToRef(tmat);
  18784. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18785. }
  18786. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18787. };
  18788. /**
  18789. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18790. */
  18791. TransformNode.prototype.getPivotPoint = function () {
  18792. var point = BABYLON.Vector3.Zero();
  18793. this.getPivotPointToRef(point);
  18794. return point;
  18795. };
  18796. /**
  18797. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18798. * Returns the TransformNode.
  18799. */
  18800. TransformNode.prototype.getPivotPointToRef = function (result) {
  18801. result.x = -this._pivotMatrix.m[12];
  18802. result.y = -this._pivotMatrix.m[13];
  18803. result.z = -this._pivotMatrix.m[14];
  18804. return this;
  18805. };
  18806. /**
  18807. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18808. */
  18809. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18810. var point = BABYLON.Vector3.Zero();
  18811. this.getAbsolutePivotPointToRef(point);
  18812. return point;
  18813. };
  18814. /**
  18815. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18816. * Returns the TransformNode.
  18817. */
  18818. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18819. result.x = this._pivotMatrix.m[12];
  18820. result.y = this._pivotMatrix.m[13];
  18821. result.z = this._pivotMatrix.m[14];
  18822. this.getPivotPointToRef(result);
  18823. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18824. return this;
  18825. };
  18826. /**
  18827. * Defines the passed node as the parent of the current node.
  18828. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18829. * Returns the TransformNode.
  18830. */
  18831. TransformNode.prototype.setParent = function (node) {
  18832. if (node === null) {
  18833. var rotation = BABYLON.Tmp.Quaternion[0];
  18834. var position = BABYLON.Tmp.Vector3[0];
  18835. var scale = BABYLON.Tmp.Vector3[1];
  18836. if (this.parent && this.parent.computeWorldMatrix) {
  18837. this.parent.computeWorldMatrix(true);
  18838. }
  18839. this.computeWorldMatrix(true);
  18840. this.getWorldMatrix().decompose(scale, rotation, position);
  18841. if (this.rotationQuaternion) {
  18842. this.rotationQuaternion.copyFrom(rotation);
  18843. }
  18844. else {
  18845. rotation.toEulerAnglesToRef(this.rotation);
  18846. }
  18847. this.scaling.x = scale.x;
  18848. this.scaling.y = scale.y;
  18849. this.scaling.z = scale.z;
  18850. this.position.x = position.x;
  18851. this.position.y = position.y;
  18852. this.position.z = position.z;
  18853. }
  18854. else {
  18855. var rotation = BABYLON.Tmp.Quaternion[0];
  18856. var position = BABYLON.Tmp.Vector3[0];
  18857. var scale = BABYLON.Tmp.Vector3[1];
  18858. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18859. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18860. this.computeWorldMatrix(true);
  18861. node.computeWorldMatrix(true);
  18862. node.getWorldMatrix().invertToRef(invParentMatrix);
  18863. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18864. diffMatrix.decompose(scale, rotation, position);
  18865. if (this.rotationQuaternion) {
  18866. this.rotationQuaternion.copyFrom(rotation);
  18867. }
  18868. else {
  18869. rotation.toEulerAnglesToRef(this.rotation);
  18870. }
  18871. this.position.x = position.x;
  18872. this.position.y = position.y;
  18873. this.position.z = position.z;
  18874. this.scaling.x = scale.x;
  18875. this.scaling.y = scale.y;
  18876. this.scaling.z = scale.z;
  18877. }
  18878. this.parent = node;
  18879. return this;
  18880. };
  18881. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18882. get: function () {
  18883. return this._nonUniformScaling;
  18884. },
  18885. enumerable: true,
  18886. configurable: true
  18887. });
  18888. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18889. if (this._nonUniformScaling === value) {
  18890. return false;
  18891. }
  18892. this._nonUniformScaling = true;
  18893. return true;
  18894. };
  18895. /**
  18896. * Attach the current TransformNode to another TransformNode associated with a bone
  18897. * @param bone Bone affecting the TransformNode
  18898. * @param affectedTransformNode TransformNode associated with the bone
  18899. */
  18900. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18901. this._transformToBoneReferal = affectedTransformNode;
  18902. this.parent = bone;
  18903. if (bone.getWorldMatrix().determinant() < 0) {
  18904. this.scalingDeterminant *= -1;
  18905. }
  18906. return this;
  18907. };
  18908. TransformNode.prototype.detachFromBone = function () {
  18909. if (!this.parent) {
  18910. return this;
  18911. }
  18912. if (this.parent.getWorldMatrix().determinant() < 0) {
  18913. this.scalingDeterminant *= -1;
  18914. }
  18915. this._transformToBoneReferal = null;
  18916. this.parent = null;
  18917. return this;
  18918. };
  18919. /**
  18920. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18921. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18922. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18923. * The passed axis is also normalized.
  18924. * Returns the TransformNode.
  18925. */
  18926. TransformNode.prototype.rotate = function (axis, amount, space) {
  18927. axis.normalize();
  18928. if (!this.rotationQuaternion) {
  18929. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18930. this.rotation = BABYLON.Vector3.Zero();
  18931. }
  18932. var rotationQuaternion;
  18933. if (!space || space === BABYLON.Space.LOCAL) {
  18934. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18935. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18936. }
  18937. else {
  18938. if (this.parent) {
  18939. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18940. invertParentWorldMatrix.invert();
  18941. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18942. }
  18943. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18944. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18945. }
  18946. return this;
  18947. };
  18948. /**
  18949. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18950. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18951. * The passed axis is also normalized.
  18952. * Returns the TransformNode.
  18953. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18954. */
  18955. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18956. axis.normalize();
  18957. if (!this.rotationQuaternion) {
  18958. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18959. this.rotation.copyFromFloats(0, 0, 0);
  18960. }
  18961. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18962. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18963. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18964. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18965. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18966. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18967. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18968. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18969. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18970. return this;
  18971. };
  18972. /**
  18973. * Translates the mesh along the axis vector for the passed distance in the given space.
  18974. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18975. * Returns the TransformNode.
  18976. */
  18977. TransformNode.prototype.translate = function (axis, distance, space) {
  18978. var displacementVector = axis.scale(distance);
  18979. if (!space || space === BABYLON.Space.LOCAL) {
  18980. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18981. this.setPositionWithLocalVector(tempV3);
  18982. }
  18983. else {
  18984. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18985. }
  18986. return this;
  18987. };
  18988. /**
  18989. * Adds a rotation step to the mesh current rotation.
  18990. * x, y, z are Euler angles expressed in radians.
  18991. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18992. * This means this rotation is made in the mesh local space only.
  18993. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18994. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18995. * ```javascript
  18996. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18997. * ```
  18998. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18999. * 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.
  19000. * Returns the TransformNode.
  19001. */
  19002. TransformNode.prototype.addRotation = function (x, y, z) {
  19003. var rotationQuaternion;
  19004. if (this.rotationQuaternion) {
  19005. rotationQuaternion = this.rotationQuaternion;
  19006. }
  19007. else {
  19008. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19009. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19010. }
  19011. var accumulation = BABYLON.Tmp.Quaternion[0];
  19012. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19013. rotationQuaternion.multiplyInPlace(accumulation);
  19014. if (!this.rotationQuaternion) {
  19015. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19016. }
  19017. return this;
  19018. };
  19019. /**
  19020. * Computes the mesh World matrix and returns it.
  19021. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19022. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19023. * If the parameter `force`is set to `true`, the actual computation is done.
  19024. * Returns the mesh World Matrix.
  19025. */
  19026. TransformNode.prototype.computeWorldMatrix = function (force) {
  19027. if (this._isWorldMatrixFrozen) {
  19028. return this._worldMatrix;
  19029. }
  19030. if (!force && this.isSynchronized(true)) {
  19031. this._currentRenderId = this.getScene().getRenderId();
  19032. return this._worldMatrix;
  19033. }
  19034. this._cache.position.copyFrom(this.position);
  19035. this._cache.scaling.copyFrom(this.scaling);
  19036. this._cache.pivotMatrixUpdated = false;
  19037. this._cache.billboardMode = this.billboardMode;
  19038. this._currentRenderId = this.getScene().getRenderId();
  19039. this._childRenderId = this.getScene().getRenderId();
  19040. this._isDirty = false;
  19041. // Scaling
  19042. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19043. // Rotation
  19044. //rotate, if quaternion is set and rotation was used
  19045. if (this.rotationQuaternion) {
  19046. var len = this.rotation.length();
  19047. if (len) {
  19048. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19049. this.rotation.copyFromFloats(0, 0, 0);
  19050. }
  19051. }
  19052. if (this.rotationQuaternion) {
  19053. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19054. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19055. }
  19056. else {
  19057. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19058. this._cache.rotation.copyFrom(this.rotation);
  19059. }
  19060. // Translation
  19061. var camera = this.getScene().activeCamera;
  19062. if (this.infiniteDistance && !this.parent && camera) {
  19063. var cameraWorldMatrix = camera.getWorldMatrix();
  19064. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19065. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19066. }
  19067. else {
  19068. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19069. }
  19070. // Composing transformations
  19071. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19072. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19073. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19074. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19075. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19076. // Need to decompose each rotation here
  19077. var currentPosition = BABYLON.Tmp.Vector3[3];
  19078. if (this.parent && this.parent.getWorldMatrix) {
  19079. if (this._transformToBoneReferal) {
  19080. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19081. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19082. }
  19083. else {
  19084. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19085. }
  19086. }
  19087. else {
  19088. currentPosition.copyFrom(this.position);
  19089. }
  19090. currentPosition.subtractInPlace(camera.globalPosition);
  19091. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19092. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19093. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19094. }
  19095. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19096. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19097. }
  19098. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19099. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19100. }
  19101. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19102. }
  19103. else {
  19104. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19105. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19106. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19107. }
  19108. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19109. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19110. }
  19111. // Local world
  19112. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19113. // Parent
  19114. if (this.parent && this.parent.getWorldMatrix) {
  19115. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19116. if (this._transformToBoneReferal) {
  19117. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19118. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19119. }
  19120. else {
  19121. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19122. }
  19123. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19124. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19125. this._worldMatrix.copyFrom(this._localWorld);
  19126. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19127. }
  19128. else {
  19129. if (this._transformToBoneReferal) {
  19130. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19131. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19132. }
  19133. else {
  19134. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19135. }
  19136. }
  19137. this._markSyncedWithParent();
  19138. }
  19139. else {
  19140. this._worldMatrix.copyFrom(this._localWorld);
  19141. }
  19142. // Post multiply inverse of pivotMatrix
  19143. if (this._postMultiplyPivotMatrix) {
  19144. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19145. }
  19146. // Normal matrix
  19147. if (this.scaling.isNonUniform) {
  19148. this._updateNonUniformScalingState(true);
  19149. }
  19150. else if (this.parent && this.parent._nonUniformScaling) {
  19151. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19152. }
  19153. else {
  19154. this._updateNonUniformScalingState(false);
  19155. }
  19156. this._afterComputeWorldMatrix();
  19157. // Absolute position
  19158. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19159. // Callbacks
  19160. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19161. if (!this._poseMatrix) {
  19162. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19163. }
  19164. // Cache the determinant
  19165. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19166. return this._worldMatrix;
  19167. };
  19168. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19169. };
  19170. /**
  19171. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19172. * @param func: callback function to add
  19173. *
  19174. * Returns the TransformNode.
  19175. */
  19176. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19177. this.onAfterWorldMatrixUpdateObservable.add(func);
  19178. return this;
  19179. };
  19180. /**
  19181. * Removes a registered callback function.
  19182. * Returns the TransformNode.
  19183. */
  19184. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19185. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19186. return this;
  19187. };
  19188. /**
  19189. * Clone the current transform node
  19190. * Returns the new transform node
  19191. * @param name Name of the new clone
  19192. * @param newParent New parent for the clone
  19193. * @param doNotCloneChildren Do not clone children hierarchy
  19194. */
  19195. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19196. var _this = this;
  19197. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19198. result.name = name;
  19199. result.id = name;
  19200. if (newParent) {
  19201. result.parent = newParent;
  19202. }
  19203. if (!doNotCloneChildren) {
  19204. // Children
  19205. var directDescendants = this.getDescendants(true);
  19206. for (var index = 0; index < directDescendants.length; index++) {
  19207. var child = directDescendants[index];
  19208. if (child.clone) {
  19209. child.clone(name + "." + child.name, result);
  19210. }
  19211. }
  19212. }
  19213. return result;
  19214. };
  19215. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19216. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19217. serializationObject.type = this.getClassName();
  19218. // Parent
  19219. if (this.parent) {
  19220. serializationObject.parentId = this.parent.id;
  19221. }
  19222. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19223. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19224. }
  19225. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19226. serializationObject.isEnabled = this.isEnabled();
  19227. // Parent
  19228. if (this.parent) {
  19229. serializationObject.parentId = this.parent.id;
  19230. }
  19231. return serializationObject;
  19232. };
  19233. // Statics
  19234. /**
  19235. * Returns a new TransformNode object parsed from the source provided.
  19236. * The parameter `parsedMesh` is the source.
  19237. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19238. */
  19239. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19240. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19241. if (BABYLON.Tags) {
  19242. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19243. }
  19244. if (parsedTransformNode.localMatrix) {
  19245. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19246. }
  19247. else if (parsedTransformNode.pivotMatrix) {
  19248. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19249. }
  19250. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19251. // Parent
  19252. if (parsedTransformNode.parentId) {
  19253. transformNode._waitingParentId = parsedTransformNode.parentId;
  19254. }
  19255. return transformNode;
  19256. };
  19257. /**
  19258. * Releases resources associated with this transform node.
  19259. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19260. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19261. */
  19262. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19263. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19264. // Animations
  19265. this.getScene().stopAnimation(this);
  19266. // Remove from scene
  19267. this.getScene().removeTransformNode(this);
  19268. this.onAfterWorldMatrixUpdateObservable.clear();
  19269. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19270. };
  19271. // Statics
  19272. TransformNode.BILLBOARDMODE_NONE = 0;
  19273. TransformNode.BILLBOARDMODE_X = 1;
  19274. TransformNode.BILLBOARDMODE_Y = 2;
  19275. TransformNode.BILLBOARDMODE_Z = 4;
  19276. TransformNode.BILLBOARDMODE_ALL = 7;
  19277. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19278. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19279. __decorate([
  19280. BABYLON.serializeAsVector3()
  19281. ], TransformNode.prototype, "_rotation", void 0);
  19282. __decorate([
  19283. BABYLON.serializeAsQuaternion()
  19284. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19285. __decorate([
  19286. BABYLON.serializeAsVector3()
  19287. ], TransformNode.prototype, "_scaling", void 0);
  19288. __decorate([
  19289. BABYLON.serialize()
  19290. ], TransformNode.prototype, "billboardMode", void 0);
  19291. __decorate([
  19292. BABYLON.serialize()
  19293. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19294. __decorate([
  19295. BABYLON.serialize()
  19296. ], TransformNode.prototype, "infiniteDistance", void 0);
  19297. __decorate([
  19298. BABYLON.serializeAsVector3()
  19299. ], TransformNode.prototype, "position", void 0);
  19300. return TransformNode;
  19301. }(BABYLON.Node));
  19302. BABYLON.TransformNode = TransformNode;
  19303. })(BABYLON || (BABYLON = {}));
  19304. //# sourceMappingURL=babylon.transformNode.js.map
  19305. var BABYLON;
  19306. (function (BABYLON) {
  19307. /**
  19308. * Class used to store all common mesh properties
  19309. */
  19310. var AbstractMesh = /** @class */ (function (_super) {
  19311. __extends(AbstractMesh, _super);
  19312. // Constructor
  19313. /**
  19314. * Creates a new AbstractMesh
  19315. * @param name defines the name of the mesh
  19316. * @param scene defines the hosting scene
  19317. */
  19318. function AbstractMesh(name, scene) {
  19319. if (scene === void 0) { scene = null; }
  19320. var _this = _super.call(this, name, scene, false) || this;
  19321. _this._facetNb = 0; // facet number
  19322. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19323. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19324. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19325. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19326. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19327. _this._subDiv = {
  19328. max: 1,
  19329. X: 1,
  19330. Y: 1,
  19331. Z: 1
  19332. };
  19333. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19334. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19335. // Events
  19336. /**
  19337. * An event triggered when this mesh collides with another one
  19338. */
  19339. _this.onCollideObservable = new BABYLON.Observable();
  19340. /**
  19341. * An event triggered when the collision's position changes
  19342. */
  19343. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19344. /**
  19345. * An event triggered when material is changed
  19346. */
  19347. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19348. // Properties
  19349. /**
  19350. * Gets or sets the orientation for POV movement & rotation
  19351. */
  19352. _this.definedFacingForward = true;
  19353. /**
  19354. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19355. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19356. * * 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.
  19357. * @see http://doc.babylonjs.com/features/occlusionquery
  19358. */
  19359. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19360. /**
  19361. * 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:
  19362. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19363. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19364. * * 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.
  19365. * @see http://doc.babylonjs.com/features/occlusionquery
  19366. */
  19367. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19368. /**
  19369. * 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.
  19370. * The default value is -1 which means don't break the query and wait till the result
  19371. * @see http://doc.babylonjs.com/features/occlusionquery
  19372. */
  19373. _this.occlusionRetryCount = -1;
  19374. _this._occlusionInternalRetryCounter = 0;
  19375. _this._isOccluded = false;
  19376. _this._isOcclusionQueryInProgress = false;
  19377. _this._visibility = 1.0;
  19378. /** Gets or sets the alpha index used to sort transparent meshes
  19379. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19380. */
  19381. _this.alphaIndex = Number.MAX_VALUE;
  19382. /**
  19383. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19384. */
  19385. _this.isVisible = true;
  19386. /**
  19387. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19388. */
  19389. _this.isPickable = true;
  19390. /**
  19391. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19392. */
  19393. _this.showBoundingBox = false;
  19394. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19395. _this.showSubMeshesBoundingBox = false;
  19396. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19397. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19398. */
  19399. _this.isBlocker = false;
  19400. /**
  19401. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19402. */
  19403. _this.enablePointerMoveEvents = false;
  19404. /**
  19405. * Specifies the rendering group id for this mesh (0 by default)
  19406. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19407. */
  19408. _this.renderingGroupId = 0;
  19409. _this._receiveShadows = false;
  19410. /**
  19411. * Gets or sets a boolean indicating if the outline must be rendered as well
  19412. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19413. */
  19414. _this.renderOutline = false;
  19415. /** Defines color to use when rendering outline */
  19416. _this.outlineColor = BABYLON.Color3.Red();
  19417. /** Define width to use when rendering outline */
  19418. _this.outlineWidth = 0.02;
  19419. /**
  19420. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19421. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19422. */
  19423. _this.renderOverlay = false;
  19424. /** Defines color to use when rendering overlay */
  19425. _this.overlayColor = BABYLON.Color3.Red();
  19426. /** Defines alpha to use when rendering overlay */
  19427. _this.overlayAlpha = 0.5;
  19428. _this._hasVertexAlpha = false;
  19429. _this._useVertexColors = true;
  19430. _this._computeBonesUsingShaders = true;
  19431. _this._numBoneInfluencers = 4;
  19432. _this._applyFog = true;
  19433. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19434. _this.useOctreeForRenderingSelection = true;
  19435. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19436. _this.useOctreeForPicking = true;
  19437. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19438. _this.useOctreeForCollisions = true;
  19439. _this._layerMask = 0x0FFFFFFF;
  19440. /**
  19441. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19442. */
  19443. _this.alwaysSelectAsActiveMesh = false;
  19444. /**
  19445. * Gets or sets the current action manager
  19446. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19447. */
  19448. _this.actionManager = null;
  19449. /**
  19450. * Gets or sets impostor used for physic simulation
  19451. * @see http://doc.babylonjs.com/features/physics_engine
  19452. */
  19453. _this.physicsImpostor = null;
  19454. // Collisions
  19455. _this._checkCollisions = false;
  19456. _this._collisionMask = -1;
  19457. _this._collisionGroup = -1;
  19458. /**
  19459. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19460. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19461. */
  19462. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19463. /**
  19464. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19465. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19466. */
  19467. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19468. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19469. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19470. // Edges
  19471. /**
  19472. * Defines edge width used when edgesRenderer is enabled
  19473. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19474. */
  19475. _this.edgesWidth = 1;
  19476. /**
  19477. * Defines edge color used when edgesRenderer is enabled
  19478. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19479. */
  19480. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19481. // Cache
  19482. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19483. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19484. /** @hidden */
  19485. _this._renderId = 0;
  19486. /** @hidden */
  19487. _this._intersectionsInProgress = new Array();
  19488. /** @hidden */
  19489. _this._unIndexed = false;
  19490. /** @hidden */
  19491. _this._lightSources = new Array();
  19492. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19493. if (collidedMesh === void 0) { collidedMesh = null; }
  19494. //TODO move this to the collision coordinator!
  19495. if (_this.getScene().workerCollisions)
  19496. newPosition.multiplyInPlace(_this._collider._radius);
  19497. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19498. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19499. _this.position.addInPlace(_this._diffPositionForCollisions);
  19500. }
  19501. if (collidedMesh) {
  19502. _this.onCollideObservable.notifyObservers(collidedMesh);
  19503. }
  19504. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19505. };
  19506. _this.getScene().addMesh(_this);
  19507. _this._resyncLightSources();
  19508. return _this;
  19509. }
  19510. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19511. /**
  19512. * No billboard
  19513. */
  19514. get: function () {
  19515. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19521. /** Billboard on X axis */
  19522. get: function () {
  19523. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19524. },
  19525. enumerable: true,
  19526. configurable: true
  19527. });
  19528. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19529. /** Billboard on Y axis */
  19530. get: function () {
  19531. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19537. /** Billboard on Z axis */
  19538. get: function () {
  19539. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19540. },
  19541. enumerable: true,
  19542. configurable: true
  19543. });
  19544. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19545. /** Billboard on all axes */
  19546. get: function () {
  19547. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19553. /**
  19554. * Gets the number of facets in the mesh
  19555. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19556. */
  19557. get: function () {
  19558. return this._facetNb;
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19564. /**
  19565. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19566. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19567. */
  19568. get: function () {
  19569. return this._partitioningSubdivisions;
  19570. },
  19571. set: function (nb) {
  19572. this._partitioningSubdivisions = nb;
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19578. /**
  19579. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19580. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19581. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19582. */
  19583. get: function () {
  19584. return this._partitioningBBoxRatio;
  19585. },
  19586. set: function (ratio) {
  19587. this._partitioningBBoxRatio = ratio;
  19588. },
  19589. enumerable: true,
  19590. configurable: true
  19591. });
  19592. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19593. /**
  19594. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19595. * Works only for updatable meshes.
  19596. * Doesn't work with multi-materials
  19597. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19598. */
  19599. get: function () {
  19600. return this._facetDepthSort;
  19601. },
  19602. set: function (sort) {
  19603. this._facetDepthSort = sort;
  19604. },
  19605. enumerable: true,
  19606. configurable: true
  19607. });
  19608. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19609. /**
  19610. * The location (Vector3) where the facet depth sort must be computed from.
  19611. * By default, the active camera position.
  19612. * Used only when facet depth sort is enabled
  19613. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19614. */
  19615. get: function () {
  19616. return this._facetDepthSortFrom;
  19617. },
  19618. set: function (location) {
  19619. this._facetDepthSortFrom = location;
  19620. },
  19621. enumerable: true,
  19622. configurable: true
  19623. });
  19624. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19625. /**
  19626. * gets a boolean indicating if facetData is enabled
  19627. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19628. */
  19629. get: function () {
  19630. return this._facetDataEnabled;
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. /** @hidden */
  19636. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19637. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19638. return false;
  19639. }
  19640. this._markSubMeshesAsMiscDirty();
  19641. return true;
  19642. };
  19643. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19644. /** Set a function to call when this mesh collides with another one */
  19645. set: function (callback) {
  19646. if (this._onCollideObserver) {
  19647. this.onCollideObservable.remove(this._onCollideObserver);
  19648. }
  19649. this._onCollideObserver = this.onCollideObservable.add(callback);
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19655. /** Set a function to call when the collision's position changes */
  19656. set: function (callback) {
  19657. if (this._onCollisionPositionChangeObserver) {
  19658. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19659. }
  19660. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19666. /**
  19667. * 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
  19668. * @see http://doc.babylonjs.com/features/occlusionquery
  19669. */
  19670. get: function () {
  19671. return this._isOccluded;
  19672. },
  19673. set: function (value) {
  19674. this._isOccluded = value;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19680. /**
  19681. * Flag to check the progress status of the query
  19682. * @see http://doc.babylonjs.com/features/occlusionquery
  19683. */
  19684. get: function () {
  19685. return this._isOcclusionQueryInProgress;
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19691. /**
  19692. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19693. */
  19694. get: function () {
  19695. return this._visibility;
  19696. },
  19697. /**
  19698. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19699. */
  19700. set: function (value) {
  19701. if (this._visibility === value) {
  19702. return;
  19703. }
  19704. this._visibility = value;
  19705. this._markSubMeshesAsMiscDirty();
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(AbstractMesh.prototype, "material", {
  19711. /** Gets or sets current material */
  19712. get: function () {
  19713. return this._material;
  19714. },
  19715. set: function (value) {
  19716. if (this._material === value) {
  19717. return;
  19718. }
  19719. this._material = value;
  19720. if (this.onMaterialChangedObservable.hasObservers) {
  19721. this.onMaterialChangedObservable.notifyObservers(this);
  19722. }
  19723. if (!this.subMeshes) {
  19724. return;
  19725. }
  19726. this._unBindEffect();
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19732. /**
  19733. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19734. * @see http://doc.babylonjs.com/babylon101/shadows
  19735. */
  19736. get: function () {
  19737. return this._receiveShadows;
  19738. },
  19739. set: function (value) {
  19740. if (this._receiveShadows === value) {
  19741. return;
  19742. }
  19743. this._receiveShadows = value;
  19744. this._markSubMeshesAsLightDirty();
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19750. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19751. get: function () {
  19752. return this._hasVertexAlpha;
  19753. },
  19754. set: function (value) {
  19755. if (this._hasVertexAlpha === value) {
  19756. return;
  19757. }
  19758. this._hasVertexAlpha = value;
  19759. this._markSubMeshesAsAttributesDirty();
  19760. this._markSubMeshesAsMiscDirty();
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19766. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19767. get: function () {
  19768. return this._useVertexColors;
  19769. },
  19770. set: function (value) {
  19771. if (this._useVertexColors === value) {
  19772. return;
  19773. }
  19774. this._useVertexColors = value;
  19775. this._markSubMeshesAsAttributesDirty();
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19781. /**
  19782. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19783. */
  19784. get: function () {
  19785. return this._computeBonesUsingShaders;
  19786. },
  19787. set: function (value) {
  19788. if (this._computeBonesUsingShaders === value) {
  19789. return;
  19790. }
  19791. this._computeBonesUsingShaders = value;
  19792. this._markSubMeshesAsAttributesDirty();
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19798. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19799. get: function () {
  19800. return this._numBoneInfluencers;
  19801. },
  19802. set: function (value) {
  19803. if (this._numBoneInfluencers === value) {
  19804. return;
  19805. }
  19806. this._numBoneInfluencers = value;
  19807. this._markSubMeshesAsAttributesDirty();
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19813. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19814. get: function () {
  19815. return this._applyFog;
  19816. },
  19817. set: function (value) {
  19818. if (this._applyFog === value) {
  19819. return;
  19820. }
  19821. this._applyFog = value;
  19822. this._markSubMeshesAsMiscDirty();
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19828. /**
  19829. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19830. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19831. */
  19832. get: function () {
  19833. return this._layerMask;
  19834. },
  19835. set: function (value) {
  19836. if (value === this._layerMask) {
  19837. return;
  19838. }
  19839. this._layerMask = value;
  19840. this._resyncLightSources();
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19846. /**
  19847. * Gets or sets a collision mask used to mask collisions (default is -1).
  19848. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19849. */
  19850. get: function () {
  19851. return this._collisionMask;
  19852. },
  19853. set: function (mask) {
  19854. this._collisionMask = !isNaN(mask) ? mask : -1;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19860. /**
  19861. * Gets or sets the current collision group mask (-1 by default).
  19862. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19863. */
  19864. get: function () {
  19865. return this._collisionGroup;
  19866. },
  19867. set: function (mask) {
  19868. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19874. /** @hidden */
  19875. get: function () {
  19876. return null;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19882. get: function () {
  19883. return this._skeleton;
  19884. },
  19885. /**
  19886. * Gets or sets a skeleton to apply skining transformations
  19887. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19888. */
  19889. set: function (value) {
  19890. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19891. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19892. }
  19893. if (value && value.needInitialSkinMatrix) {
  19894. value._registerMeshWithPoseMatrix(this);
  19895. }
  19896. this._skeleton = value;
  19897. if (!this._skeleton) {
  19898. this._bonesTransformMatrices = null;
  19899. }
  19900. this._markSubMeshesAsAttributesDirty();
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. /**
  19906. * Returns the string "AbstractMesh"
  19907. * @returns "AbstractMesh"
  19908. */
  19909. AbstractMesh.prototype.getClassName = function () {
  19910. return "AbstractMesh";
  19911. };
  19912. /**
  19913. * Gets a string representation of the current mesh
  19914. * @param fullDetails defines a boolean indicating if full details must be included
  19915. * @returns a string representation of the current mesh
  19916. */
  19917. AbstractMesh.prototype.toString = function (fullDetails) {
  19918. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19919. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19920. if (this._skeleton) {
  19921. ret += ", skeleton: " + this._skeleton.name;
  19922. }
  19923. if (fullDetails) {
  19924. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19925. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19926. }
  19927. return ret;
  19928. };
  19929. /** @hidden */
  19930. AbstractMesh.prototype._rebuild = function () {
  19931. if (this._occlusionQuery) {
  19932. this._occlusionQuery = null;
  19933. }
  19934. if (this._edgesRenderer) {
  19935. this._edgesRenderer._rebuild();
  19936. }
  19937. if (!this.subMeshes) {
  19938. return;
  19939. }
  19940. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19941. var subMesh = _a[_i];
  19942. subMesh._rebuild();
  19943. }
  19944. };
  19945. /** @hidden */
  19946. AbstractMesh.prototype._resyncLightSources = function () {
  19947. this._lightSources.length = 0;
  19948. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19949. var light = _a[_i];
  19950. if (!light.isEnabled()) {
  19951. continue;
  19952. }
  19953. if (light.canAffectMesh(this)) {
  19954. this._lightSources.push(light);
  19955. }
  19956. }
  19957. this._markSubMeshesAsLightDirty();
  19958. };
  19959. /** @hidden */
  19960. AbstractMesh.prototype._resyncLighSource = function (light) {
  19961. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19962. var index = this._lightSources.indexOf(light);
  19963. if (index === -1) {
  19964. if (!isIn) {
  19965. return;
  19966. }
  19967. this._lightSources.push(light);
  19968. }
  19969. else {
  19970. if (isIn) {
  19971. return;
  19972. }
  19973. this._lightSources.splice(index, 1);
  19974. }
  19975. this._markSubMeshesAsLightDirty();
  19976. };
  19977. /** @hidden */
  19978. AbstractMesh.prototype._unBindEffect = function () {
  19979. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19980. var subMesh = _a[_i];
  19981. subMesh.setEffect(null);
  19982. }
  19983. };
  19984. /** @hidden */
  19985. AbstractMesh.prototype._removeLightSource = function (light) {
  19986. var index = this._lightSources.indexOf(light);
  19987. if (index === -1) {
  19988. return;
  19989. }
  19990. this._lightSources.splice(index, 1);
  19991. this._markSubMeshesAsLightDirty();
  19992. };
  19993. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19994. if (!this.subMeshes) {
  19995. return;
  19996. }
  19997. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19998. var subMesh = _a[_i];
  19999. if (subMesh._materialDefines) {
  20000. func(subMesh._materialDefines);
  20001. }
  20002. }
  20003. };
  20004. /** @hidden */
  20005. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20006. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20007. };
  20008. /** @hidden */
  20009. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20010. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20011. };
  20012. /** @hidden */
  20013. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20014. if (!this.subMeshes) {
  20015. return;
  20016. }
  20017. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20018. var subMesh = _a[_i];
  20019. var material = subMesh.getMaterial();
  20020. if (material) {
  20021. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20022. }
  20023. }
  20024. };
  20025. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20026. /**
  20027. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20028. */
  20029. get: function () {
  20030. return this._scaling;
  20031. },
  20032. set: function (newScaling) {
  20033. this._scaling = newScaling;
  20034. if (this.physicsImpostor) {
  20035. this.physicsImpostor.forceUpdate();
  20036. }
  20037. },
  20038. enumerable: true,
  20039. configurable: true
  20040. });
  20041. // Methods
  20042. /**
  20043. * Disables the mesh edge rendering mode
  20044. * @returns the currentAbstractMesh
  20045. */
  20046. AbstractMesh.prototype.disableEdgesRendering = function () {
  20047. if (this._edgesRenderer) {
  20048. this._edgesRenderer.dispose();
  20049. this._edgesRenderer = null;
  20050. }
  20051. return this;
  20052. };
  20053. /**
  20054. * Enables the edge rendering mode on the mesh.
  20055. * This mode makes the mesh edges visible
  20056. * @param epsilon defines the maximal distance between two angles to detect a face
  20057. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20058. * @returns the currentAbstractMesh
  20059. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20060. */
  20061. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20062. if (epsilon === void 0) { epsilon = 0.95; }
  20063. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20064. this.disableEdgesRendering();
  20065. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20066. return this;
  20067. };
  20068. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20069. /**
  20070. * Returns true if the mesh is blocked. Implemented by child classes
  20071. */
  20072. get: function () {
  20073. return false;
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. /**
  20079. * Returns the mesh itself by default. Implemented by child classes
  20080. * @param camera defines the camera to use to pick the right LOD level
  20081. * @returns the currentAbstractMesh
  20082. */
  20083. AbstractMesh.prototype.getLOD = function (camera) {
  20084. return this;
  20085. };
  20086. /**
  20087. * Returns 0 by default. Implemented by child classes
  20088. * @returns an integer
  20089. */
  20090. AbstractMesh.prototype.getTotalVertices = function () {
  20091. return 0;
  20092. };
  20093. /**
  20094. * Returns null by default. Implemented by child classes
  20095. * @returns null
  20096. */
  20097. AbstractMesh.prototype.getIndices = function () {
  20098. return null;
  20099. };
  20100. /**
  20101. * Returns the array of the requested vertex data kind. Implemented by child classes
  20102. * @param kind defines the vertex data kind to use
  20103. * @returns null
  20104. */
  20105. AbstractMesh.prototype.getVerticesData = function (kind) {
  20106. return null;
  20107. };
  20108. /**
  20109. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20110. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20111. * Note that a new underlying VertexBuffer object is created each call.
  20112. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20113. * @param kind defines vertex data kind:
  20114. * * BABYLON.VertexBuffer.PositionKind
  20115. * * BABYLON.VertexBuffer.UVKind
  20116. * * BABYLON.VertexBuffer.UV2Kind
  20117. * * BABYLON.VertexBuffer.UV3Kind
  20118. * * BABYLON.VertexBuffer.UV4Kind
  20119. * * BABYLON.VertexBuffer.UV5Kind
  20120. * * BABYLON.VertexBuffer.UV6Kind
  20121. * * BABYLON.VertexBuffer.ColorKind
  20122. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20123. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20124. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20125. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20126. * @param data defines the data source
  20127. * @param updatable defines if the data must be flagged as updatable (or static)
  20128. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20129. * @returns the current mesh
  20130. */
  20131. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20132. return this;
  20133. };
  20134. /**
  20135. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20136. * If the mesh has no geometry, it is simply returned as it is.
  20137. * @param kind defines vertex data kind:
  20138. * * BABYLON.VertexBuffer.PositionKind
  20139. * * BABYLON.VertexBuffer.UVKind
  20140. * * BABYLON.VertexBuffer.UV2Kind
  20141. * * BABYLON.VertexBuffer.UV3Kind
  20142. * * BABYLON.VertexBuffer.UV4Kind
  20143. * * BABYLON.VertexBuffer.UV5Kind
  20144. * * BABYLON.VertexBuffer.UV6Kind
  20145. * * BABYLON.VertexBuffer.ColorKind
  20146. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20147. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20148. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20149. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20150. * @param data defines the data source
  20151. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20152. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20153. * @returns the current mesh
  20154. */
  20155. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20156. return this;
  20157. };
  20158. /**
  20159. * Sets the mesh indices,
  20160. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20161. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20162. * @param totalVertices Defines the total number of vertices
  20163. * @returns the current mesh
  20164. */
  20165. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20166. return this;
  20167. };
  20168. /**
  20169. * Gets a boolean indicating if specific vertex data is present
  20170. * @param kind defines the vertex data kind to use
  20171. * @returns true is data kind is present
  20172. */
  20173. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20174. return false;
  20175. };
  20176. /**
  20177. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20178. * @returns a BoundingInfo
  20179. */
  20180. AbstractMesh.prototype.getBoundingInfo = function () {
  20181. if (this._masterMesh) {
  20182. return this._masterMesh.getBoundingInfo();
  20183. }
  20184. if (!this._boundingInfo) {
  20185. // this._boundingInfo is being created here
  20186. this._updateBoundingInfo();
  20187. }
  20188. // cannot be null.
  20189. return this._boundingInfo;
  20190. };
  20191. /**
  20192. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20193. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20194. * @returns the current mesh
  20195. */
  20196. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20197. if (includeDescendants === void 0) { includeDescendants = true; }
  20198. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20199. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20200. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20201. if (maxDimension === 0) {
  20202. return this;
  20203. }
  20204. var scale = 1 / maxDimension;
  20205. this.scaling.scaleInPlace(scale);
  20206. return this;
  20207. };
  20208. /**
  20209. * Overwrite the current bounding info
  20210. * @param boundingInfo defines the new bounding info
  20211. * @returns the current mesh
  20212. */
  20213. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20214. this._boundingInfo = boundingInfo;
  20215. return this;
  20216. };
  20217. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20218. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20219. get: function () {
  20220. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20221. },
  20222. enumerable: true,
  20223. configurable: true
  20224. });
  20225. /** @hidden */
  20226. AbstractMesh.prototype._preActivate = function () {
  20227. };
  20228. /** @hidden */
  20229. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20230. };
  20231. /** @hidden */
  20232. AbstractMesh.prototype._activate = function (renderId) {
  20233. this._renderId = renderId;
  20234. };
  20235. /**
  20236. * Gets the current world matrix
  20237. * @returns a Matrix
  20238. */
  20239. AbstractMesh.prototype.getWorldMatrix = function () {
  20240. if (this._masterMesh) {
  20241. return this._masterMesh.getWorldMatrix();
  20242. }
  20243. return _super.prototype.getWorldMatrix.call(this);
  20244. };
  20245. /** @hidden */
  20246. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20247. if (this._masterMesh) {
  20248. return this._masterMesh._getWorldMatrixDeterminant();
  20249. }
  20250. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20251. };
  20252. // ================================== Point of View Movement =================================
  20253. /**
  20254. * Perform relative position change from the point of view of behind the front of the mesh.
  20255. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20256. * Supports definition of mesh facing forward or backward
  20257. * @param amountRight defines the distance on the right axis
  20258. * @param amountUp defines the distance on the up axis
  20259. * @param amountForward defines the distance on the forward axis
  20260. * @returns the current mesh
  20261. */
  20262. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20263. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20264. return this;
  20265. };
  20266. /**
  20267. * Calculate relative position change from the point of view of behind the front of the mesh.
  20268. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20269. * Supports definition of mesh facing forward or backward
  20270. * @param amountRight defines the distance on the right axis
  20271. * @param amountUp defines the distance on the up axis
  20272. * @param amountForward defines the distance on the forward axis
  20273. * @returns the new displacement vector
  20274. */
  20275. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20276. var rotMatrix = new BABYLON.Matrix();
  20277. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20278. rotQuaternion.toRotationMatrix(rotMatrix);
  20279. var translationDelta = BABYLON.Vector3.Zero();
  20280. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20281. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20282. return translationDelta;
  20283. };
  20284. // ================================== Point of View Rotation =================================
  20285. /**
  20286. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20287. * Supports definition of mesh facing forward or backward
  20288. * @param flipBack defines the flip
  20289. * @param twirlClockwise defines the twirl
  20290. * @param tiltRight defines the tilt
  20291. * @returns the current mesh
  20292. */
  20293. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20294. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20295. return this;
  20296. };
  20297. /**
  20298. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20299. * Supports definition of mesh facing forward or backward.
  20300. * @param flipBack defines the flip
  20301. * @param twirlClockwise defines the twirl
  20302. * @param tiltRight defines the tilt
  20303. * @returns the new rotation vector
  20304. */
  20305. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20306. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20307. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20308. };
  20309. /**
  20310. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20311. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20312. * @returns the new bounding vectors
  20313. */
  20314. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20315. if (includeDescendants === void 0) { includeDescendants = true; }
  20316. // Ensures that all world matrix will be recomputed.
  20317. this.getScene().incrementRenderId();
  20318. this.computeWorldMatrix(true);
  20319. var min;
  20320. var max;
  20321. var boundingInfo = this.getBoundingInfo();
  20322. if (!this.subMeshes) {
  20323. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20324. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20325. }
  20326. else {
  20327. min = boundingInfo.boundingBox.minimumWorld;
  20328. max = boundingInfo.boundingBox.maximumWorld;
  20329. }
  20330. if (includeDescendants) {
  20331. var descendants = this.getDescendants(false);
  20332. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20333. var descendant = descendants_1[_i];
  20334. var childMesh = descendant;
  20335. childMesh.computeWorldMatrix(true);
  20336. //make sure we have the needed params to get mix and max
  20337. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20338. continue;
  20339. }
  20340. var childBoundingInfo = childMesh.getBoundingInfo();
  20341. var boundingBox = childBoundingInfo.boundingBox;
  20342. var minBox = boundingBox.minimumWorld;
  20343. var maxBox = boundingBox.maximumWorld;
  20344. BABYLON.Tools.CheckExtends(minBox, min, max);
  20345. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20346. }
  20347. }
  20348. return {
  20349. min: min,
  20350. max: max
  20351. };
  20352. };
  20353. /** @hidden */
  20354. AbstractMesh.prototype._updateBoundingInfo = function () {
  20355. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20356. this._boundingInfo.update(this.worldMatrixFromCache);
  20357. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20358. return this;
  20359. };
  20360. /** @hidden */
  20361. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20362. if (!this.subMeshes) {
  20363. return this;
  20364. }
  20365. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20366. var subMesh = this.subMeshes[subIndex];
  20367. if (!subMesh.IsGlobal) {
  20368. subMesh.updateBoundingInfo(matrix);
  20369. }
  20370. }
  20371. return this;
  20372. };
  20373. /** @hidden */
  20374. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20375. // Bounding info
  20376. this._updateBoundingInfo();
  20377. };
  20378. /**
  20379. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20380. * A mesh is in the frustum if its bounding box intersects the frustum
  20381. * @param frustumPlanes defines the frustum to test
  20382. * @returns true if the mesh is in the frustum planes
  20383. */
  20384. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20385. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20386. };
  20387. /**
  20388. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20389. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20390. * @param frustumPlanes defines the frustum to test
  20391. * @returns true if the mesh is completely in the frustum planes
  20392. */
  20393. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20394. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20395. };
  20396. /**
  20397. * True if the mesh intersects another mesh or a SolidParticle object
  20398. * @param mesh defines a target mesh or SolidParticle to test
  20399. * @param precise 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)
  20400. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20401. * @returns true if there is an intersection
  20402. */
  20403. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20404. if (precise === void 0) { precise = false; }
  20405. if (!this._boundingInfo || !mesh._boundingInfo) {
  20406. return false;
  20407. }
  20408. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20409. return true;
  20410. }
  20411. if (includeDescendants) {
  20412. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20413. var child = _a[_i];
  20414. if (child.intersectsMesh(mesh, precise, true)) {
  20415. return true;
  20416. }
  20417. }
  20418. }
  20419. return false;
  20420. };
  20421. /**
  20422. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20423. * @param point defines the point to test
  20424. * @returns true if there is an intersection
  20425. */
  20426. AbstractMesh.prototype.intersectsPoint = function (point) {
  20427. if (!this._boundingInfo) {
  20428. return false;
  20429. }
  20430. return this._boundingInfo.intersectsPoint(point);
  20431. };
  20432. /**
  20433. * Gets the current physics impostor
  20434. * @see http://doc.babylonjs.com/features/physics_engine
  20435. * @returns a physics impostor or null
  20436. */
  20437. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20438. return this.physicsImpostor;
  20439. };
  20440. /**
  20441. * Gets the position of the current mesh in camera space
  20442. * @param camera defines the camera to use
  20443. * @returns a position
  20444. */
  20445. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20446. if (camera === void 0) { camera = null; }
  20447. if (!camera) {
  20448. camera = this.getScene().activeCamera;
  20449. }
  20450. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20451. };
  20452. /**
  20453. * Returns the distance from the mesh to the active camera
  20454. * @param camera defines the camera to use
  20455. * @returns the distance
  20456. */
  20457. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20458. if (camera === void 0) { camera = null; }
  20459. if (!camera) {
  20460. camera = this.getScene().activeCamera;
  20461. }
  20462. return this.absolutePosition.subtract(camera.position).length();
  20463. };
  20464. /**
  20465. * Apply a physic impulse to the mesh
  20466. * @param force defines the force to apply
  20467. * @param contactPoint defines where to apply the force
  20468. * @returns the current mesh
  20469. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20470. */
  20471. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20472. if (!this.physicsImpostor) {
  20473. return this;
  20474. }
  20475. this.physicsImpostor.applyImpulse(force, contactPoint);
  20476. return this;
  20477. };
  20478. /**
  20479. * Creates a physic joint between two meshes
  20480. * @param otherMesh defines the other mesh to use
  20481. * @param pivot1 defines the pivot to use on this mesh
  20482. * @param pivot2 defines the pivot to use on the other mesh
  20483. * @param options defines additional options (can be plugin dependent)
  20484. * @returns the current mesh
  20485. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20486. */
  20487. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20488. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20489. return this;
  20490. }
  20491. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20492. mainPivot: pivot1,
  20493. connectedPivot: pivot2,
  20494. nativeParams: options
  20495. });
  20496. return this;
  20497. };
  20498. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20499. // Collisions
  20500. /**
  20501. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20502. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20503. */
  20504. get: function () {
  20505. return this._checkCollisions;
  20506. },
  20507. set: function (collisionEnabled) {
  20508. this._checkCollisions = collisionEnabled;
  20509. if (this.getScene().workerCollisions) {
  20510. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20511. }
  20512. },
  20513. enumerable: true,
  20514. configurable: true
  20515. });
  20516. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20517. /**
  20518. * Gets Collider object used to compute collisions (not physics)
  20519. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20520. */
  20521. get: function () {
  20522. return this._collider;
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. /**
  20528. * Move the mesh using collision engine
  20529. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20530. * @param displacement defines the requested displacement vector
  20531. * @returns the current mesh
  20532. */
  20533. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20534. var globalPosition = this.getAbsolutePosition();
  20535. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20536. if (!this._collider) {
  20537. this._collider = new BABYLON.Collider();
  20538. }
  20539. this._collider._radius = this.ellipsoid;
  20540. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20541. return this;
  20542. };
  20543. // Submeshes octree
  20544. /**
  20545. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20546. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20547. * @param maxCapacity defines the maximum size of each block (64 by default)
  20548. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20549. * @returns the new octree
  20550. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20551. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20552. */
  20553. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20554. if (maxCapacity === void 0) { maxCapacity = 64; }
  20555. if (maxDepth === void 0) { maxDepth = 2; }
  20556. if (!this._submeshesOctree) {
  20557. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20558. }
  20559. this.computeWorldMatrix(true);
  20560. var boundingInfo = this.getBoundingInfo();
  20561. // Update octree
  20562. var bbox = boundingInfo.boundingBox;
  20563. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20564. return this._submeshesOctree;
  20565. };
  20566. // Collisions
  20567. /** @hidden */
  20568. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20569. this._generatePointsArray();
  20570. if (!this._positions) {
  20571. return this;
  20572. }
  20573. // Transformation
  20574. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20575. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20576. subMesh._lastColliderWorldVertices = [];
  20577. subMesh._trianglePlanes = [];
  20578. var start = subMesh.verticesStart;
  20579. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20580. for (var i = start; i < end; i++) {
  20581. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20582. }
  20583. }
  20584. // Collide
  20585. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20586. if (collider.collisionFound) {
  20587. collider.collidedMesh = this;
  20588. }
  20589. return this;
  20590. };
  20591. /** @hidden */
  20592. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20593. var subMeshes;
  20594. var len;
  20595. // Octrees
  20596. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20597. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20598. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20599. len = intersections.length;
  20600. subMeshes = intersections.data;
  20601. }
  20602. else {
  20603. subMeshes = this.subMeshes;
  20604. len = subMeshes.length;
  20605. }
  20606. for (var index = 0; index < len; index++) {
  20607. var subMesh = subMeshes[index];
  20608. // Bounding test
  20609. if (len > 1 && !subMesh._checkCollision(collider))
  20610. continue;
  20611. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20612. }
  20613. return this;
  20614. };
  20615. /** @hidden */
  20616. AbstractMesh.prototype._checkCollision = function (collider) {
  20617. // Bounding box test
  20618. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20619. return this;
  20620. // Transformation matrix
  20621. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20622. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20623. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20624. return this;
  20625. };
  20626. // Picking
  20627. /** @hidden */
  20628. AbstractMesh.prototype._generatePointsArray = function () {
  20629. return false;
  20630. };
  20631. /**
  20632. * Checks if the passed Ray intersects with the mesh
  20633. * @param ray defines the ray to use
  20634. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20635. * @returns the picking info
  20636. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20637. */
  20638. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20639. var pickingInfo = new BABYLON.PickingInfo();
  20640. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20641. return pickingInfo;
  20642. }
  20643. if (!this._generatePointsArray()) {
  20644. return pickingInfo;
  20645. }
  20646. var intersectInfo = null;
  20647. // Octrees
  20648. var subMeshes;
  20649. var len;
  20650. if (this._submeshesOctree && this.useOctreeForPicking) {
  20651. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20652. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20653. len = intersections.length;
  20654. subMeshes = intersections.data;
  20655. }
  20656. else {
  20657. subMeshes = this.subMeshes;
  20658. len = subMeshes.length;
  20659. }
  20660. for (var index = 0; index < len; index++) {
  20661. var subMesh = subMeshes[index];
  20662. // Bounding test
  20663. if (len > 1 && !subMesh.canIntersects(ray))
  20664. continue;
  20665. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20666. if (currentIntersectInfo) {
  20667. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20668. intersectInfo = currentIntersectInfo;
  20669. intersectInfo.subMeshId = index;
  20670. if (fastCheck) {
  20671. break;
  20672. }
  20673. }
  20674. }
  20675. }
  20676. if (intersectInfo) {
  20677. // Get picked point
  20678. var world = this.getWorldMatrix();
  20679. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20680. var direction = ray.direction.clone();
  20681. direction = direction.scale(intersectInfo.distance);
  20682. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20683. var pickedPoint = worldOrigin.add(worldDirection);
  20684. // Return result
  20685. pickingInfo.hit = true;
  20686. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20687. pickingInfo.pickedPoint = pickedPoint;
  20688. pickingInfo.pickedMesh = this;
  20689. pickingInfo.bu = intersectInfo.bu || 0;
  20690. pickingInfo.bv = intersectInfo.bv || 0;
  20691. pickingInfo.faceId = intersectInfo.faceId;
  20692. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20693. return pickingInfo;
  20694. }
  20695. return pickingInfo;
  20696. };
  20697. /**
  20698. * Clones the current mesh
  20699. * @param name defines the mesh name
  20700. * @param newParent defines the new mesh parent
  20701. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20702. * @returns the new mesh
  20703. */
  20704. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20705. return null;
  20706. };
  20707. /**
  20708. * Disposes all the submeshes of the current meshnp
  20709. * @returns the current mesh
  20710. */
  20711. AbstractMesh.prototype.releaseSubMeshes = function () {
  20712. if (this.subMeshes) {
  20713. while (this.subMeshes.length) {
  20714. this.subMeshes[0].dispose();
  20715. }
  20716. }
  20717. else {
  20718. this.subMeshes = new Array();
  20719. }
  20720. return this;
  20721. };
  20722. /**
  20723. * Releases resources associated with this abstract mesh.
  20724. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20725. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20726. */
  20727. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20728. var _this = this;
  20729. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20730. var index;
  20731. // Smart Array Retainers.
  20732. this.getScene().freeActiveMeshes();
  20733. this.getScene().freeRenderingGroups();
  20734. // Action manager
  20735. if (this.actionManager !== undefined && this.actionManager !== null) {
  20736. this.actionManager.dispose();
  20737. this.actionManager = null;
  20738. }
  20739. // Skeleton
  20740. this._skeleton = null;
  20741. // Physics
  20742. if (this.physicsImpostor) {
  20743. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20744. }
  20745. // Intersections in progress
  20746. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20747. var other = this._intersectionsInProgress[index];
  20748. var pos = other._intersectionsInProgress.indexOf(this);
  20749. other._intersectionsInProgress.splice(pos, 1);
  20750. }
  20751. this._intersectionsInProgress = [];
  20752. // Lights
  20753. var lights = this.getScene().lights;
  20754. lights.forEach(function (light) {
  20755. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20756. if (meshIndex !== -1) {
  20757. light.includedOnlyMeshes.splice(meshIndex, 1);
  20758. }
  20759. meshIndex = light.excludedMeshes.indexOf(_this);
  20760. if (meshIndex !== -1) {
  20761. light.excludedMeshes.splice(meshIndex, 1);
  20762. }
  20763. // Shadow generators
  20764. var generator = light.getShadowGenerator();
  20765. if (generator) {
  20766. var shadowMap = generator.getShadowMap();
  20767. if (shadowMap && shadowMap.renderList) {
  20768. meshIndex = shadowMap.renderList.indexOf(_this);
  20769. if (meshIndex !== -1) {
  20770. shadowMap.renderList.splice(meshIndex, 1);
  20771. }
  20772. }
  20773. }
  20774. });
  20775. // Edges
  20776. if (this._edgesRenderer) {
  20777. this._edgesRenderer.dispose();
  20778. this._edgesRenderer = null;
  20779. }
  20780. // SubMeshes
  20781. if (this.getClassName() !== "InstancedMesh") {
  20782. this.releaseSubMeshes();
  20783. }
  20784. // Octree
  20785. var sceneOctree = this.getScene().selectionOctree;
  20786. if (sceneOctree !== undefined && sceneOctree !== null) {
  20787. var index = sceneOctree.dynamicContent.indexOf(this);
  20788. if (index !== -1) {
  20789. sceneOctree.dynamicContent.splice(index, 1);
  20790. }
  20791. }
  20792. // Query
  20793. var engine = this.getScene().getEngine();
  20794. if (this._occlusionQuery) {
  20795. this._isOcclusionQueryInProgress = false;
  20796. engine.deleteQuery(this._occlusionQuery);
  20797. this._occlusionQuery = null;
  20798. }
  20799. // Engine
  20800. engine.wipeCaches();
  20801. // Remove from scene
  20802. this.getScene().removeMesh(this);
  20803. if (disposeMaterialAndTextures) {
  20804. if (this.material) {
  20805. this.material.dispose(false, true);
  20806. }
  20807. }
  20808. if (!doNotRecurse) {
  20809. // Particles
  20810. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20811. if (this.getScene().particleSystems[index].emitter === this) {
  20812. this.getScene().particleSystems[index].dispose();
  20813. index--;
  20814. }
  20815. }
  20816. }
  20817. // facet data
  20818. if (this._facetDataEnabled) {
  20819. this.disableFacetData();
  20820. }
  20821. this.onAfterWorldMatrixUpdateObservable.clear();
  20822. this.onCollideObservable.clear();
  20823. this.onCollisionPositionChangeObservable.clear();
  20824. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20825. };
  20826. /**
  20827. * Adds the passed mesh as a child to the current mesh
  20828. * @param mesh defines the child mesh
  20829. * @returns the current mesh
  20830. */
  20831. AbstractMesh.prototype.addChild = function (mesh) {
  20832. mesh.setParent(this);
  20833. return this;
  20834. };
  20835. /**
  20836. * Removes the passed mesh from the current mesh children list
  20837. * @param mesh defines the child mesh
  20838. * @returns the current mesh
  20839. */
  20840. AbstractMesh.prototype.removeChild = function (mesh) {
  20841. mesh.setParent(null);
  20842. return this;
  20843. };
  20844. // Facet data
  20845. /** @hidden */
  20846. AbstractMesh.prototype._initFacetData = function () {
  20847. if (!this._facetNormals) {
  20848. this._facetNormals = new Array();
  20849. }
  20850. if (!this._facetPositions) {
  20851. this._facetPositions = new Array();
  20852. }
  20853. if (!this._facetPartitioning) {
  20854. this._facetPartitioning = new Array();
  20855. }
  20856. this._facetNb = (this.getIndices().length / 3) | 0;
  20857. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20858. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20859. for (var f = 0; f < this._facetNb; f++) {
  20860. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20861. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20862. }
  20863. this._facetDataEnabled = true;
  20864. return this;
  20865. };
  20866. /**
  20867. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20868. * This method can be called within the render loop.
  20869. * 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
  20870. * @returns the current mesh
  20871. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20872. */
  20873. AbstractMesh.prototype.updateFacetData = function () {
  20874. if (!this._facetDataEnabled) {
  20875. this._initFacetData();
  20876. }
  20877. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20878. var indices = this.getIndices();
  20879. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20880. var bInfo = this.getBoundingInfo();
  20881. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20882. // init arrays, matrix and sort function on first call
  20883. this._facetDepthSortEnabled = true;
  20884. if (indices instanceof Uint16Array) {
  20885. this._depthSortedIndices = new Uint16Array(indices);
  20886. }
  20887. else if (indices instanceof Uint32Array) {
  20888. this._depthSortedIndices = new Uint32Array(indices);
  20889. }
  20890. else {
  20891. var needs32bits = false;
  20892. for (var i = 0; i < indices.length; i++) {
  20893. if (indices[i] > 65535) {
  20894. needs32bits = true;
  20895. break;
  20896. }
  20897. }
  20898. if (needs32bits) {
  20899. this._depthSortedIndices = new Uint32Array(indices);
  20900. }
  20901. else {
  20902. this._depthSortedIndices = new Uint16Array(indices);
  20903. }
  20904. }
  20905. this._facetDepthSortFunction = function (f1, f2) {
  20906. return (f2.sqDistance - f1.sqDistance);
  20907. };
  20908. if (!this._facetDepthSortFrom) {
  20909. var camera = this.getScene().activeCamera;
  20910. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20911. }
  20912. this._depthSortedFacets = [];
  20913. for (var f = 0; f < this._facetNb; f++) {
  20914. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20915. this._depthSortedFacets.push(depthSortedFacet);
  20916. }
  20917. this._invertedMatrix = BABYLON.Matrix.Identity();
  20918. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20919. }
  20920. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20921. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20922. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20923. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20924. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20925. this._subDiv.max = this._partitioningSubdivisions;
  20926. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20927. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20928. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20929. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20930. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20931. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20932. // set the parameters for ComputeNormals()
  20933. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20934. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20935. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20936. this._facetParameters.bInfo = bInfo;
  20937. this._facetParameters.bbSize = this._bbSize;
  20938. this._facetParameters.subDiv = this._subDiv;
  20939. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20940. this._facetParameters.depthSort = this._facetDepthSort;
  20941. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20942. this.computeWorldMatrix(true);
  20943. this._worldMatrix.invertToRef(this._invertedMatrix);
  20944. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20945. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20946. }
  20947. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20948. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20949. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20950. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20951. var l = (this._depthSortedIndices.length / 3) | 0;
  20952. for (var f = 0; f < l; f++) {
  20953. var sind = this._depthSortedFacets[f].ind;
  20954. this._depthSortedIndices[f * 3] = indices[sind];
  20955. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20956. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20957. }
  20958. this.updateIndices(this._depthSortedIndices);
  20959. }
  20960. return this;
  20961. };
  20962. /**
  20963. * Returns the facetLocalNormals array.
  20964. * The normals are expressed in the mesh local spac
  20965. * @returns an array of Vector3
  20966. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20967. */
  20968. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20969. if (!this._facetNormals) {
  20970. this.updateFacetData();
  20971. }
  20972. return this._facetNormals;
  20973. };
  20974. /**
  20975. * Returns the facetLocalPositions array.
  20976. * The facet positions are expressed in the mesh local space
  20977. * @returns an array of Vector3
  20978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20979. */
  20980. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20981. if (!this._facetPositions) {
  20982. this.updateFacetData();
  20983. }
  20984. return this._facetPositions;
  20985. };
  20986. /**
  20987. * Returns the facetLocalPartioning array
  20988. * @returns an array of array of numbers
  20989. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20990. */
  20991. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20992. if (!this._facetPartitioning) {
  20993. this.updateFacetData();
  20994. }
  20995. return this._facetPartitioning;
  20996. };
  20997. /**
  20998. * Returns the i-th facet position in the world system.
  20999. * This method allocates a new Vector3 per call
  21000. * @param i defines the facet index
  21001. * @returns a new Vector3
  21002. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21003. */
  21004. AbstractMesh.prototype.getFacetPosition = function (i) {
  21005. var pos = BABYLON.Vector3.Zero();
  21006. this.getFacetPositionToRef(i, pos);
  21007. return pos;
  21008. };
  21009. /**
  21010. * Sets the reference Vector3 with the i-th facet position in the world system
  21011. * @param i defines the facet index
  21012. * @param ref defines the target vector
  21013. * @returns the current mesh
  21014. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21015. */
  21016. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21017. var localPos = (this.getFacetLocalPositions())[i];
  21018. var world = this.getWorldMatrix();
  21019. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21020. return this;
  21021. };
  21022. /**
  21023. * Returns the i-th facet normal in the world system.
  21024. * This method allocates a new Vector3 per call
  21025. * @param i defines the facet index
  21026. * @returns a new Vector3
  21027. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21028. */
  21029. AbstractMesh.prototype.getFacetNormal = function (i) {
  21030. var norm = BABYLON.Vector3.Zero();
  21031. this.getFacetNormalToRef(i, norm);
  21032. return norm;
  21033. };
  21034. /**
  21035. * Sets the reference Vector3 with the i-th facet normal in the world system
  21036. * @param i defines the facet index
  21037. * @param ref defines the target vector
  21038. * @returns the current mesh
  21039. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21040. */
  21041. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21042. var localNorm = (this.getFacetLocalNormals())[i];
  21043. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21044. return this;
  21045. };
  21046. /**
  21047. * 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)
  21048. * @param x defines x coordinate
  21049. * @param y defines y coordinate
  21050. * @param z defines z coordinate
  21051. * @returns the array of facet indexes
  21052. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21053. */
  21054. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21055. var bInfo = this.getBoundingInfo();
  21056. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21057. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21058. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21059. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21060. return null;
  21061. }
  21062. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21063. };
  21064. /**
  21065. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21066. * @param projected sets as the (x,y,z) world projection on the facet
  21067. * @param checkFace if 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
  21068. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21069. * @param x defines x coordinate
  21070. * @param y defines y coordinate
  21071. * @param z defines z coordinate
  21072. * @returns the face index if found (or null instead)
  21073. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21074. */
  21075. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21076. if (checkFace === void 0) { checkFace = false; }
  21077. if (facing === void 0) { facing = true; }
  21078. var world = this.getWorldMatrix();
  21079. var invMat = BABYLON.Tmp.Matrix[5];
  21080. world.invertToRef(invMat);
  21081. var invVect = BABYLON.Tmp.Vector3[8];
  21082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21083. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21084. if (projected) {
  21085. // tranform the local computed projected vector to world coordinates
  21086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21087. }
  21088. return closest;
  21089. };
  21090. /**
  21091. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21092. * @param projected sets as the (x,y,z) local projection on the facet
  21093. * @param checkFace if 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
  21094. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21095. * @param x defines x coordinate
  21096. * @param y defines y coordinate
  21097. * @param z defines z coordinate
  21098. * @returns the face index if found (or null instead)
  21099. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21100. */
  21101. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21102. if (checkFace === void 0) { checkFace = false; }
  21103. if (facing === void 0) { facing = true; }
  21104. var closest = null;
  21105. var tmpx = 0.0;
  21106. var tmpy = 0.0;
  21107. var tmpz = 0.0;
  21108. var d = 0.0; // tmp dot facet normal * facet position
  21109. var t0 = 0.0;
  21110. var projx = 0.0;
  21111. var projy = 0.0;
  21112. var projz = 0.0;
  21113. // Get all the facets in the same partitioning block than (x, y, z)
  21114. var facetPositions = this.getFacetLocalPositions();
  21115. var facetNormals = this.getFacetLocalNormals();
  21116. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21117. if (!facetsInBlock) {
  21118. return null;
  21119. }
  21120. // Get the closest facet to (x, y, z)
  21121. var shortest = Number.MAX_VALUE; // init distance vars
  21122. var tmpDistance = shortest;
  21123. var fib; // current facet in the block
  21124. var norm; // current facet normal
  21125. var p0; // current facet barycenter position
  21126. // loop on all the facets in the current partitioning block
  21127. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21128. fib = facetsInBlock[idx];
  21129. norm = facetNormals[fib];
  21130. p0 = facetPositions[fib];
  21131. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21132. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21133. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21134. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21135. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21136. projx = x + norm.x * t0;
  21137. projy = y + norm.y * t0;
  21138. projz = z + norm.z * t0;
  21139. tmpx = projx - x;
  21140. tmpy = projy - y;
  21141. tmpz = projz - z;
  21142. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21143. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21144. shortest = tmpDistance;
  21145. closest = fib;
  21146. if (projected) {
  21147. projected.x = projx;
  21148. projected.y = projy;
  21149. projected.z = projz;
  21150. }
  21151. }
  21152. }
  21153. }
  21154. return closest;
  21155. };
  21156. /**
  21157. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21158. * @returns the parameters
  21159. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21160. */
  21161. AbstractMesh.prototype.getFacetDataParameters = function () {
  21162. return this._facetParameters;
  21163. };
  21164. /**
  21165. * Disables the feature FacetData and frees the related memory
  21166. * @returns the current mesh
  21167. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21168. */
  21169. AbstractMesh.prototype.disableFacetData = function () {
  21170. if (this._facetDataEnabled) {
  21171. this._facetDataEnabled = false;
  21172. this._facetPositions = new Array();
  21173. this._facetNormals = new Array();
  21174. this._facetPartitioning = new Array();
  21175. this._facetParameters = null;
  21176. this._depthSortedIndices = new Uint32Array(0);
  21177. }
  21178. return this;
  21179. };
  21180. /**
  21181. * Updates the AbstractMesh indices array
  21182. * @param indices defines the data source
  21183. * @returns the current mesh
  21184. */
  21185. AbstractMesh.prototype.updateIndices = function (indices) {
  21186. return this;
  21187. };
  21188. /**
  21189. * Creates new normals data for the mesh
  21190. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21191. * @returns the current mesh
  21192. */
  21193. AbstractMesh.prototype.createNormals = function (updatable) {
  21194. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21195. var indices = this.getIndices();
  21196. var normals;
  21197. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21198. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21199. }
  21200. else {
  21201. normals = [];
  21202. }
  21203. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21204. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21205. return this;
  21206. };
  21207. /**
  21208. * Align the mesh with a normal
  21209. * @param normal defines the normal to use
  21210. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21211. * @returns the current mesh
  21212. */
  21213. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21214. if (!upDirection) {
  21215. upDirection = BABYLON.Axis.Y;
  21216. }
  21217. var axisX = BABYLON.Tmp.Vector3[0];
  21218. var axisZ = BABYLON.Tmp.Vector3[1];
  21219. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21220. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21221. if (this.rotationQuaternion) {
  21222. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21223. }
  21224. else {
  21225. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21226. }
  21227. return this;
  21228. };
  21229. /** @hidden */
  21230. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21231. var engine = this.getEngine();
  21232. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21233. this._isOccluded = false;
  21234. return;
  21235. }
  21236. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21237. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21238. if (isOcclusionQueryAvailable) {
  21239. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21240. this._isOcclusionQueryInProgress = false;
  21241. this._occlusionInternalRetryCounter = 0;
  21242. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21243. }
  21244. else {
  21245. this._occlusionInternalRetryCounter++;
  21246. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21247. this._isOcclusionQueryInProgress = false;
  21248. this._occlusionInternalRetryCounter = 0;
  21249. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21250. // if strict continue the last state of the object.
  21251. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21252. }
  21253. else {
  21254. return;
  21255. }
  21256. }
  21257. }
  21258. var scene = this.getScene();
  21259. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21260. if (!this._occlusionQuery) {
  21261. this._occlusionQuery = engine.createQuery();
  21262. }
  21263. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21264. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21265. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21266. this._isOcclusionQueryInProgress = true;
  21267. };
  21268. /** No occlusion */
  21269. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21270. /** Occlusion set to optimisitic */
  21271. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21272. /** Occlusion set to strict */
  21273. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21274. /** Use an accurante occlusion algorithm */
  21275. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21276. /** Use a conservative occlusion algorithm */
  21277. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21278. return AbstractMesh;
  21279. }(BABYLON.TransformNode));
  21280. BABYLON.AbstractMesh = AbstractMesh;
  21281. })(BABYLON || (BABYLON = {}));
  21282. //# sourceMappingURL=babylon.abstractMesh.js.map
  21283. var BABYLON;
  21284. (function (BABYLON) {
  21285. /**
  21286. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21287. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21288. * 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.
  21289. */
  21290. var Light = /** @class */ (function (_super) {
  21291. __extends(Light, _super);
  21292. /**
  21293. * Creates a Light object in the scene.
  21294. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21295. * @param name The firendly name of the light
  21296. * @param scene The scene the light belongs too
  21297. */
  21298. function Light(name, scene) {
  21299. var _this = _super.call(this, name, scene) || this;
  21300. /**
  21301. * Diffuse gives the basic color to an object.
  21302. */
  21303. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21304. /**
  21305. * Specular produces a highlight color on an object.
  21306. * Note: This is note affecting PBR materials.
  21307. */
  21308. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21309. /**
  21310. * Strength of the light.
  21311. * Note: By default it is define in the framework own unit.
  21312. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21313. */
  21314. _this.intensity = 1.0;
  21315. /**
  21316. * Defines how far from the source the light is impacting in scene units.
  21317. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21318. */
  21319. _this.range = Number.MAX_VALUE;
  21320. /**
  21321. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21322. * of light.
  21323. */
  21324. _this._photometricScale = 1.0;
  21325. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21326. _this._radius = 0.00001;
  21327. /**
  21328. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21329. * exceeding the number allowed of the materials.
  21330. */
  21331. _this.renderPriority = 0;
  21332. _this._shadowEnabled = true;
  21333. _this._excludeWithLayerMask = 0;
  21334. _this._includeOnlyWithLayerMask = 0;
  21335. _this._lightmapMode = 0;
  21336. /**
  21337. * @hidden Internal use only.
  21338. */
  21339. _this._excludedMeshesIds = new Array();
  21340. /**
  21341. * @hidden Internal use only.
  21342. */
  21343. _this._includedOnlyMeshesIds = new Array();
  21344. _this.getScene().addLight(_this);
  21345. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21346. _this._buildUniformLayout();
  21347. _this.includedOnlyMeshes = new Array();
  21348. _this.excludedMeshes = new Array();
  21349. _this._resyncMeshes();
  21350. return _this;
  21351. }
  21352. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21353. /**
  21354. * If every light affecting the material is in this lightmapMode,
  21355. * material.lightmapTexture adds or multiplies
  21356. * (depends on material.useLightmapAsShadowmap)
  21357. * after every other light calculations.
  21358. */
  21359. get: function () {
  21360. return Light._LIGHTMAP_DEFAULT;
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21366. /**
  21367. * material.lightmapTexture as only diffuse lighting from this light
  21368. * adds only specular lighting from this light
  21369. * adds dynamic shadows
  21370. */
  21371. get: function () {
  21372. return Light._LIGHTMAP_SPECULAR;
  21373. },
  21374. enumerable: true,
  21375. configurable: true
  21376. });
  21377. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21378. /**
  21379. * material.lightmapTexture as only lighting
  21380. * no light calculation from this light
  21381. * only adds dynamic shadows from this light
  21382. */
  21383. get: function () {
  21384. return Light._LIGHTMAP_SHADOWSONLY;
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21390. /**
  21391. * Each light type uses the default quantity according to its type:
  21392. * point/spot lights use luminous intensity
  21393. * directional lights use illuminance
  21394. */
  21395. get: function () {
  21396. return Light._INTENSITYMODE_AUTOMATIC;
  21397. },
  21398. enumerable: true,
  21399. configurable: true
  21400. });
  21401. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21402. /**
  21403. * lumen (lm)
  21404. */
  21405. get: function () {
  21406. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21407. },
  21408. enumerable: true,
  21409. configurable: true
  21410. });
  21411. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21412. /**
  21413. * candela (lm/sr)
  21414. */
  21415. get: function () {
  21416. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21417. },
  21418. enumerable: true,
  21419. configurable: true
  21420. });
  21421. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21422. /**
  21423. * lux (lm/m^2)
  21424. */
  21425. get: function () {
  21426. return Light._INTENSITYMODE_ILLUMINANCE;
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21432. /**
  21433. * nit (cd/m^2)
  21434. */
  21435. get: function () {
  21436. return Light._INTENSITYMODE_LUMINANCE;
  21437. },
  21438. enumerable: true,
  21439. configurable: true
  21440. });
  21441. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21442. /**
  21443. * Light type const id of the point light.
  21444. */
  21445. get: function () {
  21446. return Light._LIGHTTYPEID_POINTLIGHT;
  21447. },
  21448. enumerable: true,
  21449. configurable: true
  21450. });
  21451. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21452. /**
  21453. * Light type const id of the directional light.
  21454. */
  21455. get: function () {
  21456. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21462. /**
  21463. * Light type const id of the spot light.
  21464. */
  21465. get: function () {
  21466. return Light._LIGHTTYPEID_SPOTLIGHT;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21472. /**
  21473. * Light type const id of the hemispheric light.
  21474. */
  21475. get: function () {
  21476. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. Object.defineProperty(Light.prototype, "intensityMode", {
  21482. /**
  21483. * Gets the photometric scale used to interpret the intensity.
  21484. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21485. */
  21486. get: function () {
  21487. return this._intensityMode;
  21488. },
  21489. /**
  21490. * Sets the photometric scale used to interpret the intensity.
  21491. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21492. */
  21493. set: function (value) {
  21494. this._intensityMode = value;
  21495. this._computePhotometricScale();
  21496. },
  21497. enumerable: true,
  21498. configurable: true
  21499. });
  21500. ;
  21501. ;
  21502. Object.defineProperty(Light.prototype, "radius", {
  21503. /**
  21504. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21505. */
  21506. get: function () {
  21507. return this._radius;
  21508. },
  21509. /**
  21510. * sets the light radius used by PBR Materials to simulate soft area lights.
  21511. */
  21512. set: function (value) {
  21513. this._radius = value;
  21514. this._computePhotometricScale();
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. ;
  21520. ;
  21521. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21522. /**
  21523. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21524. * the current shadow generator.
  21525. */
  21526. get: function () {
  21527. return this._shadowEnabled;
  21528. },
  21529. /**
  21530. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21531. * the current shadow generator.
  21532. */
  21533. set: function (value) {
  21534. if (this._shadowEnabled === value) {
  21535. return;
  21536. }
  21537. this._shadowEnabled = value;
  21538. this._markMeshesAsLightDirty();
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21544. /**
  21545. * Gets the only meshes impacted by this light.
  21546. */
  21547. get: function () {
  21548. return this._includedOnlyMeshes;
  21549. },
  21550. /**
  21551. * Sets the only meshes impacted by this light.
  21552. */
  21553. set: function (value) {
  21554. this._includedOnlyMeshes = value;
  21555. this._hookArrayForIncludedOnly(value);
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21561. /**
  21562. * Gets the meshes not impacted by this light.
  21563. */
  21564. get: function () {
  21565. return this._excludedMeshes;
  21566. },
  21567. /**
  21568. * Sets the meshes not impacted by this light.
  21569. */
  21570. set: function (value) {
  21571. this._excludedMeshes = value;
  21572. this._hookArrayForExcluded(value);
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21578. /**
  21579. * Gets the layer id use to find what meshes are not impacted by the light.
  21580. * Inactive if 0
  21581. */
  21582. get: function () {
  21583. return this._excludeWithLayerMask;
  21584. },
  21585. /**
  21586. * Sets the layer id use to find what meshes are not impacted by the light.
  21587. * Inactive if 0
  21588. */
  21589. set: function (value) {
  21590. this._excludeWithLayerMask = value;
  21591. this._resyncMeshes();
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21597. /**
  21598. * Gets the layer id use to find what meshes are impacted by the light.
  21599. * Inactive if 0
  21600. */
  21601. get: function () {
  21602. return this._includeOnlyWithLayerMask;
  21603. },
  21604. /**
  21605. * Sets the layer id use to find what meshes are impacted by the light.
  21606. * Inactive if 0
  21607. */
  21608. set: function (value) {
  21609. this._includeOnlyWithLayerMask = value;
  21610. this._resyncMeshes();
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Light.prototype, "lightmapMode", {
  21616. /**
  21617. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21618. */
  21619. get: function () {
  21620. return this._lightmapMode;
  21621. },
  21622. /**
  21623. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21624. */
  21625. set: function (value) {
  21626. if (this._lightmapMode === value) {
  21627. return;
  21628. }
  21629. this._lightmapMode = value;
  21630. this._markMeshesAsLightDirty();
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. /**
  21636. * Returns the string "Light".
  21637. * @returns the class name
  21638. */
  21639. Light.prototype.getClassName = function () {
  21640. return "Light";
  21641. };
  21642. /**
  21643. * Converts the light information to a readable string for debug purpose.
  21644. * @param fullDetails Supports for multiple levels of logging within scene loading
  21645. * @returns the human readable light info
  21646. */
  21647. Light.prototype.toString = function (fullDetails) {
  21648. var ret = "Name: " + this.name;
  21649. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21650. if (this.animations) {
  21651. for (var i = 0; i < this.animations.length; i++) {
  21652. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21653. }
  21654. }
  21655. if (fullDetails) {
  21656. }
  21657. return ret;
  21658. };
  21659. /**
  21660. * Set the enabled state of this node.
  21661. * @param value - the new enabled state
  21662. */
  21663. Light.prototype.setEnabled = function (value) {
  21664. _super.prototype.setEnabled.call(this, value);
  21665. this._resyncMeshes();
  21666. };
  21667. /**
  21668. * Returns the Light associated shadow generator if any.
  21669. * @return the associated shadow generator.
  21670. */
  21671. Light.prototype.getShadowGenerator = function () {
  21672. return this._shadowGenerator;
  21673. };
  21674. /**
  21675. * Returns a Vector3, the absolute light position in the World.
  21676. * @returns the world space position of the light
  21677. */
  21678. Light.prototype.getAbsolutePosition = function () {
  21679. return BABYLON.Vector3.Zero();
  21680. };
  21681. /**
  21682. * Specifies if the light will affect the passed mesh.
  21683. * @param mesh The mesh to test against the light
  21684. * @return true the mesh is affected otherwise, false.
  21685. */
  21686. Light.prototype.canAffectMesh = function (mesh) {
  21687. if (!mesh) {
  21688. return true;
  21689. }
  21690. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21691. return false;
  21692. }
  21693. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21694. return false;
  21695. }
  21696. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21697. return false;
  21698. }
  21699. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21700. return false;
  21701. }
  21702. return true;
  21703. };
  21704. /**
  21705. * Computes and Returns the light World matrix.
  21706. * @returns the world matrix
  21707. */
  21708. Light.prototype.getWorldMatrix = function () {
  21709. this._currentRenderId = this.getScene().getRenderId();
  21710. this._childRenderId = this._currentRenderId;
  21711. var worldMatrix = this._getWorldMatrix();
  21712. if (this.parent && this.parent.getWorldMatrix) {
  21713. if (!this._parentedWorldMatrix) {
  21714. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21715. }
  21716. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21717. this._markSyncedWithParent();
  21718. return this._parentedWorldMatrix;
  21719. }
  21720. return worldMatrix;
  21721. };
  21722. /**
  21723. * Sort function to order lights for rendering.
  21724. * @param a First Light object to compare to second.
  21725. * @param b Second Light object to compare first.
  21726. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21727. */
  21728. Light.CompareLightsPriority = function (a, b) {
  21729. //shadow-casting lights have priority over non-shadow-casting lights
  21730. //the renderPrioirty is a secondary sort criterion
  21731. if (a.shadowEnabled !== b.shadowEnabled) {
  21732. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21733. }
  21734. return b.renderPriority - a.renderPriority;
  21735. };
  21736. /**
  21737. * Releases resources associated with this node.
  21738. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21739. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21740. */
  21741. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21742. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21743. if (this._shadowGenerator) {
  21744. this._shadowGenerator.dispose();
  21745. this._shadowGenerator = null;
  21746. }
  21747. // Animations
  21748. this.getScene().stopAnimation(this);
  21749. // Remove from meshes
  21750. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21751. var mesh = _a[_i];
  21752. mesh._removeLightSource(this);
  21753. }
  21754. this._uniformBuffer.dispose();
  21755. // Remove from scene
  21756. this.getScene().removeLight(this);
  21757. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21758. };
  21759. /**
  21760. * Returns the light type ID (integer).
  21761. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21762. */
  21763. Light.prototype.getTypeID = function () {
  21764. return 0;
  21765. };
  21766. /**
  21767. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21768. * @returns the scaled intensity in intensity mode unit
  21769. */
  21770. Light.prototype.getScaledIntensity = function () {
  21771. return this._photometricScale * this.intensity;
  21772. };
  21773. /**
  21774. * Returns a new Light object, named "name", from the current one.
  21775. * @param name The name of the cloned light
  21776. * @returns the new created light
  21777. */
  21778. Light.prototype.clone = function (name) {
  21779. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21780. if (!constructor) {
  21781. return null;
  21782. }
  21783. return BABYLON.SerializationHelper.Clone(constructor, this);
  21784. };
  21785. /**
  21786. * Serializes the current light into a Serialization object.
  21787. * @returns the serialized object.
  21788. */
  21789. Light.prototype.serialize = function () {
  21790. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21791. // Type
  21792. serializationObject.type = this.getTypeID();
  21793. // Parent
  21794. if (this.parent) {
  21795. serializationObject.parentId = this.parent.id;
  21796. }
  21797. // Inclusion / exclusions
  21798. if (this.excludedMeshes.length > 0) {
  21799. serializationObject.excludedMeshesIds = [];
  21800. this.excludedMeshes.forEach(function (mesh) {
  21801. serializationObject.excludedMeshesIds.push(mesh.id);
  21802. });
  21803. }
  21804. if (this.includedOnlyMeshes.length > 0) {
  21805. serializationObject.includedOnlyMeshesIds = [];
  21806. this.includedOnlyMeshes.forEach(function (mesh) {
  21807. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21808. });
  21809. }
  21810. // Animations
  21811. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21812. serializationObject.ranges = this.serializeAnimationRanges();
  21813. return serializationObject;
  21814. };
  21815. /**
  21816. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21817. * This new light is named "name" and added to the passed scene.
  21818. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21819. * @param name The friendly name of the light
  21820. * @param scene The scene the new light will belong to
  21821. * @returns the constructor function
  21822. */
  21823. Light.GetConstructorFromName = function (type, name, scene) {
  21824. switch (type) {
  21825. case 0:
  21826. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21827. case 1:
  21828. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21829. case 2:
  21830. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21831. case 3:
  21832. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21833. }
  21834. return null;
  21835. };
  21836. /**
  21837. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21838. * @param parsedLight The JSON representation of the light
  21839. * @param scene The scene to create the parsed light in
  21840. * @returns the created light after parsing
  21841. */
  21842. Light.Parse = function (parsedLight, scene) {
  21843. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21844. if (!constructor) {
  21845. return null;
  21846. }
  21847. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21848. // Inclusion / exclusions
  21849. if (parsedLight.excludedMeshesIds) {
  21850. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21851. }
  21852. if (parsedLight.includedOnlyMeshesIds) {
  21853. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21854. }
  21855. // Parent
  21856. if (parsedLight.parentId) {
  21857. light._waitingParentId = parsedLight.parentId;
  21858. }
  21859. // Animations
  21860. if (parsedLight.animations) {
  21861. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21862. var parsedAnimation = parsedLight.animations[animationIndex];
  21863. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21864. }
  21865. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21866. }
  21867. if (parsedLight.autoAnimate) {
  21868. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21869. }
  21870. return light;
  21871. };
  21872. Light.prototype._hookArrayForExcluded = function (array) {
  21873. var _this = this;
  21874. var oldPush = array.push;
  21875. array.push = function () {
  21876. var items = [];
  21877. for (var _i = 0; _i < arguments.length; _i++) {
  21878. items[_i] = arguments[_i];
  21879. }
  21880. var result = oldPush.apply(array, items);
  21881. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21882. var item = items_1[_a];
  21883. item._resyncLighSource(_this);
  21884. }
  21885. return result;
  21886. };
  21887. var oldSplice = array.splice;
  21888. array.splice = function (index, deleteCount) {
  21889. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21890. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21891. var item = deleted_1[_i];
  21892. item._resyncLighSource(_this);
  21893. }
  21894. return deleted;
  21895. };
  21896. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21897. var item = array_1[_i];
  21898. item._resyncLighSource(this);
  21899. }
  21900. };
  21901. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21902. var _this = this;
  21903. var oldPush = array.push;
  21904. array.push = function () {
  21905. var items = [];
  21906. for (var _i = 0; _i < arguments.length; _i++) {
  21907. items[_i] = arguments[_i];
  21908. }
  21909. var result = oldPush.apply(array, items);
  21910. _this._resyncMeshes();
  21911. return result;
  21912. };
  21913. var oldSplice = array.splice;
  21914. array.splice = function (index, deleteCount) {
  21915. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21916. _this._resyncMeshes();
  21917. return deleted;
  21918. };
  21919. this._resyncMeshes();
  21920. };
  21921. Light.prototype._resyncMeshes = function () {
  21922. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21923. var mesh = _a[_i];
  21924. mesh._resyncLighSource(this);
  21925. }
  21926. };
  21927. /**
  21928. * Forces the meshes to update their light related information in their rendering used effects
  21929. * @hidden Internal Use Only
  21930. */
  21931. Light.prototype._markMeshesAsLightDirty = function () {
  21932. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21933. var mesh = _a[_i];
  21934. if (mesh._lightSources.indexOf(this) !== -1) {
  21935. mesh._markSubMeshesAsLightDirty();
  21936. }
  21937. }
  21938. };
  21939. /**
  21940. * Recomputes the cached photometric scale if needed.
  21941. */
  21942. Light.prototype._computePhotometricScale = function () {
  21943. this._photometricScale = this._getPhotometricScale();
  21944. this.getScene().resetCachedMaterial();
  21945. };
  21946. /**
  21947. * Returns the Photometric Scale according to the light type and intensity mode.
  21948. */
  21949. Light.prototype._getPhotometricScale = function () {
  21950. var photometricScale = 0.0;
  21951. var lightTypeID = this.getTypeID();
  21952. //get photometric mode
  21953. var photometricMode = this.intensityMode;
  21954. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21955. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21956. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21957. }
  21958. else {
  21959. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21960. }
  21961. }
  21962. //compute photometric scale
  21963. switch (lightTypeID) {
  21964. case Light.LIGHTTYPEID_POINTLIGHT:
  21965. case Light.LIGHTTYPEID_SPOTLIGHT:
  21966. switch (photometricMode) {
  21967. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21968. photometricScale = 1.0 / (4.0 * Math.PI);
  21969. break;
  21970. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21971. photometricScale = 1.0;
  21972. break;
  21973. case Light.INTENSITYMODE_LUMINANCE:
  21974. photometricScale = this.radius * this.radius;
  21975. break;
  21976. }
  21977. break;
  21978. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21979. switch (photometricMode) {
  21980. case Light.INTENSITYMODE_ILLUMINANCE:
  21981. photometricScale = 1.0;
  21982. break;
  21983. case Light.INTENSITYMODE_LUMINANCE:
  21984. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21985. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21986. var apexAngleRadians = this.radius;
  21987. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21988. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21989. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21990. photometricScale = solidAngle;
  21991. break;
  21992. }
  21993. break;
  21994. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21995. // No fall off in hemisperic light.
  21996. photometricScale = 1.0;
  21997. break;
  21998. }
  21999. return photometricScale;
  22000. };
  22001. /**
  22002. * Reorder the light in the scene according to their defined priority.
  22003. * @hidden Internal Use Only
  22004. */
  22005. Light.prototype._reorderLightsInScene = function () {
  22006. var scene = this.getScene();
  22007. if (this._renderPriority != 0) {
  22008. scene.requireLightSorting = true;
  22009. }
  22010. this.getScene().sortLightsByPriority();
  22011. };
  22012. //lightmapMode Consts
  22013. Light._LIGHTMAP_DEFAULT = 0;
  22014. Light._LIGHTMAP_SPECULAR = 1;
  22015. Light._LIGHTMAP_SHADOWSONLY = 2;
  22016. // Intensity Mode Consts
  22017. Light._INTENSITYMODE_AUTOMATIC = 0;
  22018. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22019. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22020. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22021. Light._INTENSITYMODE_LUMINANCE = 4;
  22022. // Light types ids const.
  22023. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22024. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22025. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22026. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22027. __decorate([
  22028. BABYLON.serializeAsColor3()
  22029. ], Light.prototype, "diffuse", void 0);
  22030. __decorate([
  22031. BABYLON.serializeAsColor3()
  22032. ], Light.prototype, "specular", void 0);
  22033. __decorate([
  22034. BABYLON.serialize()
  22035. ], Light.prototype, "intensity", void 0);
  22036. __decorate([
  22037. BABYLON.serialize()
  22038. ], Light.prototype, "range", void 0);
  22039. __decorate([
  22040. BABYLON.serialize()
  22041. ], Light.prototype, "intensityMode", null);
  22042. __decorate([
  22043. BABYLON.serialize()
  22044. ], Light.prototype, "radius", null);
  22045. __decorate([
  22046. BABYLON.serialize()
  22047. ], Light.prototype, "_renderPriority", void 0);
  22048. __decorate([
  22049. BABYLON.expandToProperty("_reorderLightsInScene")
  22050. ], Light.prototype, "renderPriority", void 0);
  22051. __decorate([
  22052. BABYLON.serialize("shadowEnabled")
  22053. ], Light.prototype, "_shadowEnabled", void 0);
  22054. __decorate([
  22055. BABYLON.serialize("excludeWithLayerMask")
  22056. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22057. __decorate([
  22058. BABYLON.serialize("includeOnlyWithLayerMask")
  22059. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22060. __decorate([
  22061. BABYLON.serialize("lightmapMode")
  22062. ], Light.prototype, "_lightmapMode", void 0);
  22063. return Light;
  22064. }(BABYLON.Node));
  22065. BABYLON.Light = Light;
  22066. })(BABYLON || (BABYLON = {}));
  22067. //# sourceMappingURL=babylon.light.js.map
  22068. var BABYLON;
  22069. (function (BABYLON) {
  22070. var Camera = /** @class */ (function (_super) {
  22071. __extends(Camera, _super);
  22072. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22073. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22074. var _this = _super.call(this, name, scene) || this;
  22075. /**
  22076. * The vector the camera should consider as up.
  22077. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22078. */
  22079. _this.upVector = BABYLON.Vector3.Up();
  22080. _this.orthoLeft = null;
  22081. _this.orthoRight = null;
  22082. _this.orthoBottom = null;
  22083. _this.orthoTop = null;
  22084. /**
  22085. * FOV is set in Radians. (default is 0.8)
  22086. */
  22087. _this.fov = 0.8;
  22088. _this.minZ = 1;
  22089. _this.maxZ = 10000.0;
  22090. _this.inertia = 0.9;
  22091. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22092. _this.isIntermediate = false;
  22093. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22094. /**
  22095. * Restricts the camera to viewing objects with the same layerMask.
  22096. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22097. */
  22098. _this.layerMask = 0x0FFFFFFF;
  22099. /**
  22100. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22101. */
  22102. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22103. // Camera rig members
  22104. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22105. _this._rigCameras = new Array();
  22106. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22107. _this._skipRendering = false;
  22108. _this.customRenderTargets = new Array();
  22109. // Observables
  22110. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22111. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22112. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22113. _this.onRestoreStateObservable = new BABYLON.Observable();
  22114. // Cache
  22115. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22116. _this._projectionMatrix = new BABYLON.Matrix();
  22117. _this._doNotComputeProjectionMatrix = false;
  22118. _this._worldMatrix = BABYLON.Matrix.Identity();
  22119. _this._postProcesses = new Array();
  22120. _this._transformMatrix = BABYLON.Matrix.Zero();
  22121. _this._activeMeshes = new BABYLON.SmartArray(256);
  22122. _this._globalPosition = BABYLON.Vector3.Zero();
  22123. _this._refreshFrustumPlanes = true;
  22124. _this.getScene().addCamera(_this);
  22125. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22126. _this.getScene().activeCamera = _this;
  22127. }
  22128. _this.position = position;
  22129. return _this;
  22130. }
  22131. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22132. get: function () {
  22133. return Camera._PERSPECTIVE_CAMERA;
  22134. },
  22135. enumerable: true,
  22136. configurable: true
  22137. });
  22138. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22139. get: function () {
  22140. return Camera._ORTHOGRAPHIC_CAMERA;
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22146. /**
  22147. * This is the default FOV mode for perspective cameras.
  22148. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22149. *
  22150. */
  22151. get: function () {
  22152. return Camera._FOVMODE_VERTICAL_FIXED;
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22158. /**
  22159. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22160. *
  22161. */
  22162. get: function () {
  22163. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22169. get: function () {
  22170. return Camera._RIG_MODE_NONE;
  22171. },
  22172. enumerable: true,
  22173. configurable: true
  22174. });
  22175. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22176. get: function () {
  22177. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22178. },
  22179. enumerable: true,
  22180. configurable: true
  22181. });
  22182. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22183. get: function () {
  22184. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22190. get: function () {
  22191. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22197. get: function () {
  22198. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22199. },
  22200. enumerable: true,
  22201. configurable: true
  22202. });
  22203. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22204. get: function () {
  22205. return Camera._RIG_MODE_VR;
  22206. },
  22207. enumerable: true,
  22208. configurable: true
  22209. });
  22210. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22211. get: function () {
  22212. return Camera._RIG_MODE_WEBVR;
  22213. },
  22214. enumerable: true,
  22215. configurable: true
  22216. });
  22217. /**
  22218. * Store current camera state (fov, position, etc..)
  22219. */
  22220. Camera.prototype.storeState = function () {
  22221. this._stateStored = true;
  22222. this._storedFov = this.fov;
  22223. return this;
  22224. };
  22225. /**
  22226. * Restores the camera state values if it has been stored. You must call storeState() first
  22227. */
  22228. Camera.prototype._restoreStateValues = function () {
  22229. if (!this._stateStored) {
  22230. return false;
  22231. }
  22232. this.fov = this._storedFov;
  22233. return true;
  22234. };
  22235. /**
  22236. * Restored camera state. You must call storeState() first
  22237. */
  22238. Camera.prototype.restoreState = function () {
  22239. if (this._restoreStateValues()) {
  22240. this.onRestoreStateObservable.notifyObservers(this);
  22241. return true;
  22242. }
  22243. return false;
  22244. };
  22245. Camera.prototype.getClassName = function () {
  22246. return "Camera";
  22247. };
  22248. /**
  22249. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22250. */
  22251. Camera.prototype.toString = function (fullDetails) {
  22252. var ret = "Name: " + this.name;
  22253. ret += ", type: " + this.getClassName();
  22254. if (this.animations) {
  22255. for (var i = 0; i < this.animations.length; i++) {
  22256. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22257. }
  22258. }
  22259. if (fullDetails) {
  22260. }
  22261. return ret;
  22262. };
  22263. Object.defineProperty(Camera.prototype, "globalPosition", {
  22264. get: function () {
  22265. return this._globalPosition;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Camera.prototype.getActiveMeshes = function () {
  22271. return this._activeMeshes;
  22272. };
  22273. Camera.prototype.isActiveMesh = function (mesh) {
  22274. return (this._activeMeshes.indexOf(mesh) !== -1);
  22275. };
  22276. /**
  22277. * Is this camera ready to be used/rendered
  22278. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22279. * @return true if the camera is ready
  22280. */
  22281. Camera.prototype.isReady = function (completeCheck) {
  22282. if (completeCheck === void 0) { completeCheck = false; }
  22283. if (completeCheck) {
  22284. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22285. var pp = _a[_i];
  22286. if (pp && !pp.isReady()) {
  22287. return false;
  22288. }
  22289. }
  22290. }
  22291. return _super.prototype.isReady.call(this, completeCheck);
  22292. };
  22293. //Cache
  22294. Camera.prototype._initCache = function () {
  22295. _super.prototype._initCache.call(this);
  22296. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22297. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22298. this._cache.mode = undefined;
  22299. this._cache.minZ = undefined;
  22300. this._cache.maxZ = undefined;
  22301. this._cache.fov = undefined;
  22302. this._cache.fovMode = undefined;
  22303. this._cache.aspectRatio = undefined;
  22304. this._cache.orthoLeft = undefined;
  22305. this._cache.orthoRight = undefined;
  22306. this._cache.orthoBottom = undefined;
  22307. this._cache.orthoTop = undefined;
  22308. this._cache.renderWidth = undefined;
  22309. this._cache.renderHeight = undefined;
  22310. };
  22311. Camera.prototype._updateCache = function (ignoreParentClass) {
  22312. if (!ignoreParentClass) {
  22313. _super.prototype._updateCache.call(this);
  22314. }
  22315. this._cache.position.copyFrom(this.position);
  22316. this._cache.upVector.copyFrom(this.upVector);
  22317. };
  22318. // Synchronized
  22319. Camera.prototype._isSynchronized = function () {
  22320. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22321. };
  22322. Camera.prototype._isSynchronizedViewMatrix = function () {
  22323. if (!_super.prototype._isSynchronized.call(this))
  22324. return false;
  22325. return this._cache.position.equals(this.position)
  22326. && this._cache.upVector.equals(this.upVector)
  22327. && this.isSynchronizedWithParent();
  22328. };
  22329. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22330. var check = this._cache.mode === this.mode
  22331. && this._cache.minZ === this.minZ
  22332. && this._cache.maxZ === this.maxZ;
  22333. if (!check) {
  22334. return false;
  22335. }
  22336. var engine = this.getEngine();
  22337. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22338. check = this._cache.fov === this.fov
  22339. && this._cache.fovMode === this.fovMode
  22340. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22341. }
  22342. else {
  22343. check = this._cache.orthoLeft === this.orthoLeft
  22344. && this._cache.orthoRight === this.orthoRight
  22345. && this._cache.orthoBottom === this.orthoBottom
  22346. && this._cache.orthoTop === this.orthoTop
  22347. && this._cache.renderWidth === engine.getRenderWidth()
  22348. && this._cache.renderHeight === engine.getRenderHeight();
  22349. }
  22350. return check;
  22351. };
  22352. // Controls
  22353. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22354. };
  22355. Camera.prototype.detachControl = function (element) {
  22356. };
  22357. Camera.prototype.update = function () {
  22358. this._checkInputs();
  22359. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22360. this._updateRigCameras();
  22361. }
  22362. };
  22363. Camera.prototype._checkInputs = function () {
  22364. this.onAfterCheckInputsObservable.notifyObservers(this);
  22365. };
  22366. Object.defineProperty(Camera.prototype, "rigCameras", {
  22367. get: function () {
  22368. return this._rigCameras;
  22369. },
  22370. enumerable: true,
  22371. configurable: true
  22372. });
  22373. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22374. get: function () {
  22375. return this._rigPostProcess;
  22376. },
  22377. enumerable: true,
  22378. configurable: true
  22379. });
  22380. /**
  22381. * Internal, gets the first post proces.
  22382. * @returns the first post process to be run on this camera.
  22383. */
  22384. Camera.prototype._getFirstPostProcess = function () {
  22385. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22386. if (this._postProcesses[ppIndex] !== null) {
  22387. return this._postProcesses[ppIndex];
  22388. }
  22389. }
  22390. return null;
  22391. };
  22392. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22393. // invalidate framebuffer
  22394. var firstPostProcess = this._getFirstPostProcess();
  22395. if (firstPostProcess) {
  22396. firstPostProcess.markTextureDirty();
  22397. }
  22398. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22399. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22400. var cam = this._rigCameras[i];
  22401. var rigPostProcess = cam._rigPostProcess;
  22402. // for VR rig, there does not have to be a post process
  22403. if (rigPostProcess) {
  22404. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22405. if (isPass) {
  22406. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22407. cam.isIntermediate = this._postProcesses.length === 0;
  22408. }
  22409. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22410. rigPostProcess.markTextureDirty();
  22411. }
  22412. else {
  22413. cam._postProcesses = this._postProcesses.slice(0);
  22414. }
  22415. }
  22416. };
  22417. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22418. if (insertAt === void 0) { insertAt = null; }
  22419. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22420. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22421. return 0;
  22422. }
  22423. if (insertAt == null || insertAt < 0) {
  22424. this._postProcesses.push(postProcess);
  22425. }
  22426. else if (this._postProcesses[insertAt] === null) {
  22427. this._postProcesses[insertAt] = postProcess;
  22428. }
  22429. else {
  22430. this._postProcesses.splice(insertAt, 0, postProcess);
  22431. }
  22432. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22433. return this._postProcesses.indexOf(postProcess);
  22434. };
  22435. Camera.prototype.detachPostProcess = function (postProcess) {
  22436. var idx = this._postProcesses.indexOf(postProcess);
  22437. if (idx !== -1) {
  22438. this._postProcesses[idx] = null;
  22439. }
  22440. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22441. };
  22442. Camera.prototype.getWorldMatrix = function () {
  22443. if (this._isSynchronizedViewMatrix()) {
  22444. return this._worldMatrix;
  22445. }
  22446. // Getting the the view matrix will also compute the world matrix.
  22447. this.getViewMatrix();
  22448. return this._worldMatrix;
  22449. };
  22450. Camera.prototype._getViewMatrix = function () {
  22451. return BABYLON.Matrix.Identity();
  22452. };
  22453. Camera.prototype.getViewMatrix = function (force) {
  22454. if (!force && this._isSynchronizedViewMatrix()) {
  22455. return this._computedViewMatrix;
  22456. }
  22457. this.updateCache();
  22458. this._computedViewMatrix = this._getViewMatrix();
  22459. this._currentRenderId = this.getScene().getRenderId();
  22460. this._childRenderId = this._currentRenderId;
  22461. this._refreshFrustumPlanes = true;
  22462. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22463. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22464. }
  22465. this.onViewMatrixChangedObservable.notifyObservers(this);
  22466. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22467. return this._computedViewMatrix;
  22468. };
  22469. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22470. this._doNotComputeProjectionMatrix = true;
  22471. if (projection !== undefined) {
  22472. this._projectionMatrix = projection;
  22473. }
  22474. };
  22475. ;
  22476. Camera.prototype.unfreezeProjectionMatrix = function () {
  22477. this._doNotComputeProjectionMatrix = false;
  22478. };
  22479. ;
  22480. Camera.prototype.getProjectionMatrix = function (force) {
  22481. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22482. return this._projectionMatrix;
  22483. }
  22484. // Cache
  22485. this._cache.mode = this.mode;
  22486. this._cache.minZ = this.minZ;
  22487. this._cache.maxZ = this.maxZ;
  22488. // Matrix
  22489. this._refreshFrustumPlanes = true;
  22490. var engine = this.getEngine();
  22491. var scene = this.getScene();
  22492. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22493. this._cache.fov = this.fov;
  22494. this._cache.fovMode = this.fovMode;
  22495. this._cache.aspectRatio = engine.getAspectRatio(this);
  22496. if (this.minZ <= 0) {
  22497. this.minZ = 0.1;
  22498. }
  22499. if (scene.useRightHandedSystem) {
  22500. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22501. }
  22502. else {
  22503. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22504. }
  22505. }
  22506. else {
  22507. var halfWidth = engine.getRenderWidth() / 2.0;
  22508. var halfHeight = engine.getRenderHeight() / 2.0;
  22509. if (scene.useRightHandedSystem) {
  22510. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22511. }
  22512. else {
  22513. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22514. }
  22515. this._cache.orthoLeft = this.orthoLeft;
  22516. this._cache.orthoRight = this.orthoRight;
  22517. this._cache.orthoBottom = this.orthoBottom;
  22518. this._cache.orthoTop = this.orthoTop;
  22519. this._cache.renderWidth = engine.getRenderWidth();
  22520. this._cache.renderHeight = engine.getRenderHeight();
  22521. }
  22522. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22523. return this._projectionMatrix;
  22524. };
  22525. Camera.prototype.getTranformationMatrix = function () {
  22526. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22527. return this._transformMatrix;
  22528. };
  22529. Camera.prototype.updateFrustumPlanes = function () {
  22530. if (!this._refreshFrustumPlanes) {
  22531. return;
  22532. }
  22533. this.getTranformationMatrix();
  22534. if (!this._frustumPlanes) {
  22535. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22536. }
  22537. else {
  22538. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22539. }
  22540. this._refreshFrustumPlanes = false;
  22541. };
  22542. Camera.prototype.isInFrustum = function (target) {
  22543. this.updateFrustumPlanes();
  22544. return target.isInFrustum(this._frustumPlanes);
  22545. };
  22546. Camera.prototype.isCompletelyInFrustum = function (target) {
  22547. this.updateFrustumPlanes();
  22548. return target.isCompletelyInFrustum(this._frustumPlanes);
  22549. };
  22550. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22551. if (length === void 0) { length = 100; }
  22552. if (!transform) {
  22553. transform = this.getWorldMatrix();
  22554. }
  22555. if (!origin) {
  22556. origin = this.position;
  22557. }
  22558. var forward = new BABYLON.Vector3(0, 0, 1);
  22559. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22560. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22561. return new BABYLON.Ray(origin, direction, length);
  22562. };
  22563. /**
  22564. * Releases resources associated with this node.
  22565. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22566. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22567. */
  22568. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22569. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22570. // Observables
  22571. this.onViewMatrixChangedObservable.clear();
  22572. this.onProjectionMatrixChangedObservable.clear();
  22573. this.onAfterCheckInputsObservable.clear();
  22574. this.onRestoreStateObservable.clear();
  22575. // Inputs
  22576. if (this.inputs) {
  22577. this.inputs.clear();
  22578. }
  22579. // Animations
  22580. this.getScene().stopAnimation(this);
  22581. // Remove from scene
  22582. this.getScene().removeCamera(this);
  22583. while (this._rigCameras.length > 0) {
  22584. var camera = this._rigCameras.pop();
  22585. if (camera) {
  22586. camera.dispose();
  22587. }
  22588. }
  22589. // Postprocesses
  22590. if (this._rigPostProcess) {
  22591. this._rigPostProcess.dispose(this);
  22592. this._rigPostProcess = null;
  22593. this._postProcesses = [];
  22594. }
  22595. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22596. this._rigPostProcess = null;
  22597. this._postProcesses = [];
  22598. }
  22599. else {
  22600. var i = this._postProcesses.length;
  22601. while (--i >= 0) {
  22602. var postProcess = this._postProcesses[i];
  22603. if (postProcess) {
  22604. postProcess.dispose(this);
  22605. }
  22606. }
  22607. }
  22608. // Render targets
  22609. var i = this.customRenderTargets.length;
  22610. while (--i >= 0) {
  22611. this.customRenderTargets[i].dispose();
  22612. }
  22613. this.customRenderTargets = [];
  22614. // Active Meshes
  22615. this._activeMeshes.dispose();
  22616. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22617. };
  22618. Object.defineProperty(Camera.prototype, "leftCamera", {
  22619. // ---- Camera rigs section ----
  22620. get: function () {
  22621. if (this._rigCameras.length < 1) {
  22622. return null;
  22623. }
  22624. return this._rigCameras[0];
  22625. },
  22626. enumerable: true,
  22627. configurable: true
  22628. });
  22629. Object.defineProperty(Camera.prototype, "rightCamera", {
  22630. get: function () {
  22631. if (this._rigCameras.length < 2) {
  22632. return null;
  22633. }
  22634. return this._rigCameras[1];
  22635. },
  22636. enumerable: true,
  22637. configurable: true
  22638. });
  22639. Camera.prototype.getLeftTarget = function () {
  22640. if (this._rigCameras.length < 1) {
  22641. return null;
  22642. }
  22643. return this._rigCameras[0].getTarget();
  22644. };
  22645. Camera.prototype.getRightTarget = function () {
  22646. if (this._rigCameras.length < 2) {
  22647. return null;
  22648. }
  22649. return this._rigCameras[1].getTarget();
  22650. };
  22651. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22652. if (this.cameraRigMode === mode) {
  22653. return;
  22654. }
  22655. while (this._rigCameras.length > 0) {
  22656. var camera = this._rigCameras.pop();
  22657. if (camera) {
  22658. camera.dispose();
  22659. }
  22660. }
  22661. this.cameraRigMode = mode;
  22662. this._cameraRigParams = {};
  22663. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22664. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22665. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22666. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22667. // create the rig cameras, unless none
  22668. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22669. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22670. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22671. if (leftCamera && rightCamera) {
  22672. this._rigCameras.push(leftCamera);
  22673. this._rigCameras.push(rightCamera);
  22674. }
  22675. }
  22676. switch (this.cameraRigMode) {
  22677. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22678. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22679. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22680. break;
  22681. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22682. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22683. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22684. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22685. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22686. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22687. break;
  22688. case Camera.RIG_MODE_VR:
  22689. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22690. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22691. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22692. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22693. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22694. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22695. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22696. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22697. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22698. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22699. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22700. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22701. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22702. if (metrics.compensateDistortion) {
  22703. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22704. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22705. }
  22706. break;
  22707. case Camera.RIG_MODE_WEBVR:
  22708. if (rigParams.vrDisplay) {
  22709. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22710. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22711. //Left eye
  22712. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22713. this._rigCameras[0].setCameraRigParameter("left", true);
  22714. //leaving this for future reference
  22715. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22716. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22717. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22718. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22719. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22720. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22721. this._rigCameras[0].parent = this;
  22722. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22723. //Right eye
  22724. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22725. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22726. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22727. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22728. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22729. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22730. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22731. this._rigCameras[1].parent = this;
  22732. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22733. if (Camera.UseAlternateWebVRRendering) {
  22734. this._rigCameras[1]._skipRendering = true;
  22735. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22736. }
  22737. }
  22738. break;
  22739. }
  22740. this._cascadePostProcessesToRigCams();
  22741. this.update();
  22742. };
  22743. Camera.prototype._getVRProjectionMatrix = function () {
  22744. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22745. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22746. return this._projectionMatrix;
  22747. };
  22748. Camera.prototype._updateCameraRotationMatrix = function () {
  22749. //Here for WebVR
  22750. };
  22751. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22752. //Here for WebVR
  22753. };
  22754. /**
  22755. * This function MUST be overwritten by the different WebVR cameras available.
  22756. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22757. */
  22758. Camera.prototype._getWebVRProjectionMatrix = function () {
  22759. return BABYLON.Matrix.Identity();
  22760. };
  22761. /**
  22762. * This function MUST be overwritten by the different WebVR cameras available.
  22763. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22764. */
  22765. Camera.prototype._getWebVRViewMatrix = function () {
  22766. return BABYLON.Matrix.Identity();
  22767. };
  22768. Camera.prototype.setCameraRigParameter = function (name, value) {
  22769. if (!this._cameraRigParams) {
  22770. this._cameraRigParams = {};
  22771. }
  22772. this._cameraRigParams[name] = value;
  22773. //provisionnally:
  22774. if (name === "interaxialDistance") {
  22775. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22776. }
  22777. };
  22778. /**
  22779. * needs to be overridden by children so sub has required properties to be copied
  22780. */
  22781. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22782. return null;
  22783. };
  22784. /**
  22785. * May need to be overridden by children
  22786. */
  22787. Camera.prototype._updateRigCameras = function () {
  22788. for (var i = 0; i < this._rigCameras.length; i++) {
  22789. this._rigCameras[i].minZ = this.minZ;
  22790. this._rigCameras[i].maxZ = this.maxZ;
  22791. this._rigCameras[i].fov = this.fov;
  22792. }
  22793. // only update viewport when ANAGLYPH
  22794. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22795. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22796. }
  22797. };
  22798. Camera.prototype._setupInputs = function () {
  22799. };
  22800. Camera.prototype.serialize = function () {
  22801. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22802. // Type
  22803. serializationObject.type = this.getClassName();
  22804. // Parent
  22805. if (this.parent) {
  22806. serializationObject.parentId = this.parent.id;
  22807. }
  22808. if (this.inputs) {
  22809. this.inputs.serialize(serializationObject);
  22810. }
  22811. // Animations
  22812. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22813. serializationObject.ranges = this.serializeAnimationRanges();
  22814. return serializationObject;
  22815. };
  22816. Camera.prototype.clone = function (name) {
  22817. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22818. };
  22819. Camera.prototype.getDirection = function (localAxis) {
  22820. var result = BABYLON.Vector3.Zero();
  22821. this.getDirectionToRef(localAxis, result);
  22822. return result;
  22823. };
  22824. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22825. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22826. };
  22827. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22828. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22829. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22830. switch (type) {
  22831. case "ArcRotateCamera":
  22832. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22833. case "DeviceOrientationCamera":
  22834. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22835. case "FollowCamera":
  22836. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22837. case "ArcFollowCamera":
  22838. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22839. case "GamepadCamera":
  22840. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22841. case "TouchCamera":
  22842. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22843. case "VirtualJoysticksCamera":
  22844. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22845. case "WebVRFreeCamera":
  22846. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22847. case "WebVRGamepadCamera":
  22848. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22849. case "VRDeviceOrientationFreeCamera":
  22850. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22851. case "VRDeviceOrientationGamepadCamera":
  22852. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22853. case "AnaglyphArcRotateCamera":
  22854. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22855. case "AnaglyphFreeCamera":
  22856. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22857. case "AnaglyphGamepadCamera":
  22858. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22859. case "AnaglyphUniversalCamera":
  22860. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22861. case "StereoscopicArcRotateCamera":
  22862. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22863. case "StereoscopicFreeCamera":
  22864. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22865. case "StereoscopicGamepadCamera":
  22866. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22867. case "StereoscopicUniversalCamera":
  22868. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22869. case "FreeCamera": // Forcing Universal here
  22870. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22871. default: // Universal Camera is the default value
  22872. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22873. }
  22874. };
  22875. Camera.prototype.computeWorldMatrix = function () {
  22876. return this.getWorldMatrix();
  22877. };
  22878. Camera.Parse = function (parsedCamera, scene) {
  22879. var type = parsedCamera.type;
  22880. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22881. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22882. // Parent
  22883. if (parsedCamera.parentId) {
  22884. camera._waitingParentId = parsedCamera.parentId;
  22885. }
  22886. //If camera has an input manager, let it parse inputs settings
  22887. if (camera.inputs) {
  22888. camera.inputs.parse(parsedCamera);
  22889. camera._setupInputs();
  22890. }
  22891. if (camera.setPosition) { // need to force position
  22892. camera.position.copyFromFloats(0, 0, 0);
  22893. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22894. }
  22895. // Target
  22896. if (parsedCamera.target) {
  22897. if (camera.setTarget) {
  22898. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22899. }
  22900. }
  22901. // Apply 3d rig, when found
  22902. if (parsedCamera.cameraRigMode) {
  22903. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22904. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22905. }
  22906. // Animations
  22907. if (parsedCamera.animations) {
  22908. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22909. var parsedAnimation = parsedCamera.animations[animationIndex];
  22910. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22911. }
  22912. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22913. }
  22914. if (parsedCamera.autoAnimate) {
  22915. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22916. }
  22917. return camera;
  22918. };
  22919. // Statics
  22920. Camera._PERSPECTIVE_CAMERA = 0;
  22921. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22922. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22923. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22924. Camera._RIG_MODE_NONE = 0;
  22925. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22926. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22927. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22928. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22929. Camera._RIG_MODE_VR = 20;
  22930. Camera._RIG_MODE_WEBVR = 21;
  22931. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22932. Camera.UseAlternateWebVRRendering = false;
  22933. __decorate([
  22934. BABYLON.serializeAsVector3()
  22935. ], Camera.prototype, "position", void 0);
  22936. __decorate([
  22937. BABYLON.serializeAsVector3()
  22938. ], Camera.prototype, "upVector", void 0);
  22939. __decorate([
  22940. BABYLON.serialize()
  22941. ], Camera.prototype, "orthoLeft", void 0);
  22942. __decorate([
  22943. BABYLON.serialize()
  22944. ], Camera.prototype, "orthoRight", void 0);
  22945. __decorate([
  22946. BABYLON.serialize()
  22947. ], Camera.prototype, "orthoBottom", void 0);
  22948. __decorate([
  22949. BABYLON.serialize()
  22950. ], Camera.prototype, "orthoTop", void 0);
  22951. __decorate([
  22952. BABYLON.serialize()
  22953. ], Camera.prototype, "fov", void 0);
  22954. __decorate([
  22955. BABYLON.serialize()
  22956. ], Camera.prototype, "minZ", void 0);
  22957. __decorate([
  22958. BABYLON.serialize()
  22959. ], Camera.prototype, "maxZ", void 0);
  22960. __decorate([
  22961. BABYLON.serialize()
  22962. ], Camera.prototype, "inertia", void 0);
  22963. __decorate([
  22964. BABYLON.serialize()
  22965. ], Camera.prototype, "mode", void 0);
  22966. __decorate([
  22967. BABYLON.serialize()
  22968. ], Camera.prototype, "layerMask", void 0);
  22969. __decorate([
  22970. BABYLON.serialize()
  22971. ], Camera.prototype, "fovMode", void 0);
  22972. __decorate([
  22973. BABYLON.serialize()
  22974. ], Camera.prototype, "cameraRigMode", void 0);
  22975. __decorate([
  22976. BABYLON.serialize()
  22977. ], Camera.prototype, "interaxialDistance", void 0);
  22978. __decorate([
  22979. BABYLON.serialize()
  22980. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22981. return Camera;
  22982. }(BABYLON.Node));
  22983. BABYLON.Camera = Camera;
  22984. })(BABYLON || (BABYLON = {}));
  22985. //# sourceMappingURL=babylon.camera.js.map
  22986. var BABYLON;
  22987. (function (BABYLON) {
  22988. var RenderingManager = /** @class */ (function () {
  22989. function RenderingManager(scene) {
  22990. this._renderingGroups = new Array();
  22991. this._autoClearDepthStencil = {};
  22992. this._customOpaqueSortCompareFn = {};
  22993. this._customAlphaTestSortCompareFn = {};
  22994. this._customTransparentSortCompareFn = {};
  22995. this._renderinGroupInfo = null;
  22996. this._scene = scene;
  22997. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22998. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22999. }
  23000. }
  23001. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23002. if (depth === void 0) { depth = true; }
  23003. if (stencil === void 0) { stencil = true; }
  23004. if (this._depthStencilBufferAlreadyCleaned) {
  23005. return;
  23006. }
  23007. this._scene.getEngine().clear(null, false, depth, stencil);
  23008. this._depthStencilBufferAlreadyCleaned = true;
  23009. };
  23010. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23011. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23012. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23013. var info = null;
  23014. if (observable) {
  23015. if (!this._renderinGroupInfo) {
  23016. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23017. }
  23018. info = this._renderinGroupInfo;
  23019. info.scene = this._scene;
  23020. info.camera = this._scene.activeCamera;
  23021. }
  23022. // Dispatch sprites
  23023. if (renderSprites) {
  23024. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23025. var manager = this._scene.spriteManagers[index];
  23026. this.dispatchSprites(manager);
  23027. }
  23028. }
  23029. // Render
  23030. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23031. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23032. var renderingGroup = this._renderingGroups[index];
  23033. if (!renderingGroup && !observable)
  23034. continue;
  23035. var renderingGroupMask = 0;
  23036. // Fire PRECLEAR stage
  23037. if (observable && info) {
  23038. renderingGroupMask = Math.pow(2, index);
  23039. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23040. info.renderingGroupId = index;
  23041. observable.notifyObservers(info, renderingGroupMask);
  23042. }
  23043. // Clear depth/stencil if needed
  23044. if (RenderingManager.AUTOCLEAR) {
  23045. var autoClear = this._autoClearDepthStencil[index];
  23046. if (autoClear && autoClear.autoClear) {
  23047. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23048. }
  23049. }
  23050. if (observable && info) {
  23051. // Fire PREOPAQUE stage
  23052. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23053. observable.notifyObservers(info, renderingGroupMask);
  23054. // Fire PRETRANSPARENT stage
  23055. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23056. observable.notifyObservers(info, renderingGroupMask);
  23057. }
  23058. if (renderingGroup)
  23059. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23060. // Fire POSTTRANSPARENT stage
  23061. if (observable && info) {
  23062. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23063. observable.notifyObservers(info, renderingGroupMask);
  23064. }
  23065. }
  23066. };
  23067. RenderingManager.prototype.reset = function () {
  23068. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23069. var renderingGroup = this._renderingGroups[index];
  23070. if (renderingGroup) {
  23071. renderingGroup.prepare();
  23072. }
  23073. }
  23074. };
  23075. RenderingManager.prototype.dispose = function () {
  23076. this.freeRenderingGroups();
  23077. this._renderingGroups.length = 0;
  23078. };
  23079. /**
  23080. * Clear the info related to rendering groups preventing retention points during dispose.
  23081. */
  23082. RenderingManager.prototype.freeRenderingGroups = function () {
  23083. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23084. var renderingGroup = this._renderingGroups[index];
  23085. if (renderingGroup) {
  23086. renderingGroup.dispose();
  23087. }
  23088. }
  23089. };
  23090. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23091. if (this._renderingGroups[renderingGroupId] === undefined) {
  23092. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23093. }
  23094. };
  23095. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23096. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23097. this._prepareRenderingGroup(renderingGroupId);
  23098. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23099. };
  23100. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23101. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23102. this._prepareRenderingGroup(renderingGroupId);
  23103. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23104. };
  23105. /**
  23106. * @param subMesh The submesh to dispatch
  23107. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23108. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23109. */
  23110. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23111. if (mesh === undefined) {
  23112. mesh = subMesh.getMesh();
  23113. }
  23114. var renderingGroupId = mesh.renderingGroupId || 0;
  23115. this._prepareRenderingGroup(renderingGroupId);
  23116. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23117. };
  23118. /**
  23119. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23120. * This allowed control for front to back rendering or reversly depending of the special needs.
  23121. *
  23122. * @param renderingGroupId The rendering group id corresponding to its index
  23123. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23124. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23125. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23126. */
  23127. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23128. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23129. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23130. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23131. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23132. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23133. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23134. if (this._renderingGroups[renderingGroupId]) {
  23135. var group = this._renderingGroups[renderingGroupId];
  23136. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23137. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23138. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23139. }
  23140. };
  23141. /**
  23142. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23143. *
  23144. * @param renderingGroupId The rendering group id corresponding to its index
  23145. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23146. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23147. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23148. */
  23149. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23150. if (depth === void 0) { depth = true; }
  23151. if (stencil === void 0) { stencil = true; }
  23152. this._autoClearDepthStencil[renderingGroupId] = {
  23153. autoClear: autoClearDepthStencil,
  23154. depth: depth,
  23155. stencil: stencil
  23156. };
  23157. };
  23158. /**
  23159. * The max id used for rendering groups (not included)
  23160. */
  23161. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23162. /**
  23163. * The min id used for rendering groups (included)
  23164. */
  23165. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23166. /**
  23167. * Used to globally prevent autoclearing scenes.
  23168. */
  23169. RenderingManager.AUTOCLEAR = true;
  23170. return RenderingManager;
  23171. }());
  23172. BABYLON.RenderingManager = RenderingManager;
  23173. })(BABYLON || (BABYLON = {}));
  23174. //# sourceMappingURL=babylon.renderingManager.js.map
  23175. var BABYLON;
  23176. (function (BABYLON) {
  23177. var RenderingGroup = /** @class */ (function () {
  23178. /**
  23179. * Creates a new rendering group.
  23180. * @param index The rendering group index
  23181. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23182. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23183. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23184. */
  23185. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23186. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23187. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23188. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23189. this.index = index;
  23190. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23191. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23192. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23193. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23194. this._particleSystems = new BABYLON.SmartArray(256);
  23195. this._spriteManagers = new BABYLON.SmartArray(256);
  23196. this._edgesRenderers = new BABYLON.SmartArray(16);
  23197. this._scene = scene;
  23198. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23199. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23200. this.transparentSortCompareFn = transparentSortCompareFn;
  23201. }
  23202. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23203. /**
  23204. * Set the opaque sort comparison function.
  23205. * If null the sub meshes will be render in the order they were created
  23206. */
  23207. set: function (value) {
  23208. this._opaqueSortCompareFn = value;
  23209. if (value) {
  23210. this._renderOpaque = this.renderOpaqueSorted;
  23211. }
  23212. else {
  23213. this._renderOpaque = RenderingGroup.renderUnsorted;
  23214. }
  23215. },
  23216. enumerable: true,
  23217. configurable: true
  23218. });
  23219. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23220. /**
  23221. * Set the alpha test sort comparison function.
  23222. * If null the sub meshes will be render in the order they were created
  23223. */
  23224. set: function (value) {
  23225. this._alphaTestSortCompareFn = value;
  23226. if (value) {
  23227. this._renderAlphaTest = this.renderAlphaTestSorted;
  23228. }
  23229. else {
  23230. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23231. }
  23232. },
  23233. enumerable: true,
  23234. configurable: true
  23235. });
  23236. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23237. /**
  23238. * Set the transparent sort comparison function.
  23239. * If null the sub meshes will be render in the order they were created
  23240. */
  23241. set: function (value) {
  23242. if (value) {
  23243. this._transparentSortCompareFn = value;
  23244. }
  23245. else {
  23246. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23247. }
  23248. this._renderTransparent = this.renderTransparentSorted;
  23249. },
  23250. enumerable: true,
  23251. configurable: true
  23252. });
  23253. /**
  23254. * Render all the sub meshes contained in the group.
  23255. * @param customRenderFunction Used to override the default render behaviour of the group.
  23256. * @returns true if rendered some submeshes.
  23257. */
  23258. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23259. if (customRenderFunction) {
  23260. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23261. return;
  23262. }
  23263. var engine = this._scene.getEngine();
  23264. // Depth only
  23265. if (this._depthOnlySubMeshes.length !== 0) {
  23266. engine.setColorWrite(false);
  23267. this._renderAlphaTest(this._depthOnlySubMeshes);
  23268. engine.setColorWrite(true);
  23269. }
  23270. // Opaque
  23271. if (this._opaqueSubMeshes.length !== 0) {
  23272. this._renderOpaque(this._opaqueSubMeshes);
  23273. }
  23274. // Alpha test
  23275. if (this._alphaTestSubMeshes.length !== 0) {
  23276. this._renderAlphaTest(this._alphaTestSubMeshes);
  23277. }
  23278. var stencilState = engine.getStencilBuffer();
  23279. engine.setStencilBuffer(false);
  23280. // Sprites
  23281. if (renderSprites) {
  23282. this._renderSprites();
  23283. }
  23284. // Particles
  23285. if (renderParticles) {
  23286. this._renderParticles(activeMeshes);
  23287. }
  23288. if (this.onBeforeTransparentRendering) {
  23289. this.onBeforeTransparentRendering();
  23290. }
  23291. // Transparent
  23292. if (this._transparentSubMeshes.length !== 0) {
  23293. this._renderTransparent(this._transparentSubMeshes);
  23294. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23295. }
  23296. // Set back stencil to false in case it changes before the edge renderer.
  23297. engine.setStencilBuffer(false);
  23298. // Edges
  23299. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23300. this._edgesRenderers.data[edgesRendererIndex].render();
  23301. }
  23302. // Restore Stencil state.
  23303. engine.setStencilBuffer(stencilState);
  23304. };
  23305. /**
  23306. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23307. * @param subMeshes The submeshes to render
  23308. */
  23309. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23310. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23311. };
  23312. /**
  23313. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23314. * @param subMeshes The submeshes to render
  23315. */
  23316. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23317. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23318. };
  23319. /**
  23320. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23321. * @param subMeshes The submeshes to render
  23322. */
  23323. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23324. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23325. };
  23326. /**
  23327. * Renders the submeshes in a specified order.
  23328. * @param subMeshes The submeshes to sort before render
  23329. * @param sortCompareFn The comparison function use to sort
  23330. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23331. * @param transparent Specifies to activate blending if true
  23332. */
  23333. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23334. var subIndex = 0;
  23335. var subMesh;
  23336. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23337. for (; subIndex < subMeshes.length; subIndex++) {
  23338. subMesh = subMeshes.data[subIndex];
  23339. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23340. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23341. }
  23342. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23343. if (sortCompareFn) {
  23344. sortedArray.sort(sortCompareFn);
  23345. }
  23346. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23347. subMesh = sortedArray[subIndex];
  23348. if (transparent) {
  23349. var material = subMesh.getMaterial();
  23350. if (material && material.needDepthPrePass) {
  23351. var engine = material.getScene().getEngine();
  23352. engine.setColorWrite(false);
  23353. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23354. subMesh.render(false);
  23355. engine.setColorWrite(true);
  23356. }
  23357. }
  23358. subMesh.render(transparent);
  23359. }
  23360. };
  23361. /**
  23362. * Renders the submeshes in the order they were dispatched (no sort applied).
  23363. * @param subMeshes The submeshes to render
  23364. */
  23365. RenderingGroup.renderUnsorted = function (subMeshes) {
  23366. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23367. var submesh = subMeshes.data[subIndex];
  23368. submesh.render(false);
  23369. }
  23370. };
  23371. /**
  23372. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23373. * are rendered back to front if in the same alpha index.
  23374. *
  23375. * @param a The first submesh
  23376. * @param b The second submesh
  23377. * @returns The result of the comparison
  23378. */
  23379. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23380. // Alpha index first
  23381. if (a._alphaIndex > b._alphaIndex) {
  23382. return 1;
  23383. }
  23384. if (a._alphaIndex < b._alphaIndex) {
  23385. return -1;
  23386. }
  23387. // Then distance to camera
  23388. return RenderingGroup.backToFrontSortCompare(a, b);
  23389. };
  23390. /**
  23391. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23392. * are rendered back to front.
  23393. *
  23394. * @param a The first submesh
  23395. * @param b The second submesh
  23396. * @returns The result of the comparison
  23397. */
  23398. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23399. // Then distance to camera
  23400. if (a._distanceToCamera < b._distanceToCamera) {
  23401. return 1;
  23402. }
  23403. if (a._distanceToCamera > b._distanceToCamera) {
  23404. return -1;
  23405. }
  23406. return 0;
  23407. };
  23408. /**
  23409. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23410. * are rendered front to back (prevent overdraw).
  23411. *
  23412. * @param a The first submesh
  23413. * @param b The second submesh
  23414. * @returns The result of the comparison
  23415. */
  23416. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23417. // Then distance to camera
  23418. if (a._distanceToCamera < b._distanceToCamera) {
  23419. return -1;
  23420. }
  23421. if (a._distanceToCamera > b._distanceToCamera) {
  23422. return 1;
  23423. }
  23424. return 0;
  23425. };
  23426. /**
  23427. * Resets the different lists of submeshes to prepare a new frame.
  23428. */
  23429. RenderingGroup.prototype.prepare = function () {
  23430. this._opaqueSubMeshes.reset();
  23431. this._transparentSubMeshes.reset();
  23432. this._alphaTestSubMeshes.reset();
  23433. this._depthOnlySubMeshes.reset();
  23434. this._particleSystems.reset();
  23435. this._spriteManagers.reset();
  23436. this._edgesRenderers.reset();
  23437. };
  23438. RenderingGroup.prototype.dispose = function () {
  23439. this._opaqueSubMeshes.dispose();
  23440. this._transparentSubMeshes.dispose();
  23441. this._alphaTestSubMeshes.dispose();
  23442. this._depthOnlySubMeshes.dispose();
  23443. this._particleSystems.dispose();
  23444. this._spriteManagers.dispose();
  23445. this._edgesRenderers.dispose();
  23446. };
  23447. /**
  23448. * Inserts the submesh in its correct queue depending on its material.
  23449. * @param subMesh The submesh to dispatch
  23450. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23451. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23452. */
  23453. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23454. // Get mesh and materials if not provided
  23455. if (mesh === undefined) {
  23456. mesh = subMesh.getMesh();
  23457. }
  23458. if (material === undefined) {
  23459. material = subMesh.getMaterial();
  23460. }
  23461. if (material === null || material === undefined) {
  23462. return;
  23463. }
  23464. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23465. this._transparentSubMeshes.push(subMesh);
  23466. }
  23467. else if (material.needAlphaTesting()) { // Alpha test
  23468. if (material.needDepthPrePass) {
  23469. this._depthOnlySubMeshes.push(subMesh);
  23470. }
  23471. this._alphaTestSubMeshes.push(subMesh);
  23472. }
  23473. else {
  23474. if (material.needDepthPrePass) {
  23475. this._depthOnlySubMeshes.push(subMesh);
  23476. }
  23477. this._opaqueSubMeshes.push(subMesh); // Opaque
  23478. }
  23479. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23480. this._edgesRenderers.push(mesh._edgesRenderer);
  23481. }
  23482. };
  23483. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23484. this._spriteManagers.push(spriteManager);
  23485. };
  23486. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23487. this._particleSystems.push(particleSystem);
  23488. };
  23489. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23490. if (this._particleSystems.length === 0) {
  23491. return;
  23492. }
  23493. // Particles
  23494. var activeCamera = this._scene.activeCamera;
  23495. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23496. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23497. var particleSystem = this._particleSystems.data[particleIndex];
  23498. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23499. continue;
  23500. }
  23501. var emitter = particleSystem.emitter;
  23502. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23503. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23504. }
  23505. }
  23506. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23507. };
  23508. RenderingGroup.prototype._renderSprites = function () {
  23509. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23510. return;
  23511. }
  23512. // Sprites
  23513. var activeCamera = this._scene.activeCamera;
  23514. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23515. for (var id = 0; id < this._spriteManagers.length; id++) {
  23516. var spriteManager = this._spriteManagers.data[id];
  23517. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23518. spriteManager.render();
  23519. }
  23520. }
  23521. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23522. };
  23523. return RenderingGroup;
  23524. }());
  23525. BABYLON.RenderingGroup = RenderingGroup;
  23526. })(BABYLON || (BABYLON = {}));
  23527. //# sourceMappingURL=babylon.renderingGroup.js.map
  23528. var BABYLON;
  23529. (function (BABYLON) {
  23530. /** @hidden */
  23531. var ClickInfo = /** @class */ (function () {
  23532. function ClickInfo() {
  23533. this._singleClick = false;
  23534. this._doubleClick = false;
  23535. this._hasSwiped = false;
  23536. this._ignore = false;
  23537. }
  23538. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23539. get: function () {
  23540. return this._singleClick;
  23541. },
  23542. set: function (b) {
  23543. this._singleClick = b;
  23544. },
  23545. enumerable: true,
  23546. configurable: true
  23547. });
  23548. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23549. get: function () {
  23550. return this._doubleClick;
  23551. },
  23552. set: function (b) {
  23553. this._doubleClick = b;
  23554. },
  23555. enumerable: true,
  23556. configurable: true
  23557. });
  23558. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23559. get: function () {
  23560. return this._hasSwiped;
  23561. },
  23562. set: function (b) {
  23563. this._hasSwiped = b;
  23564. },
  23565. enumerable: true,
  23566. configurable: true
  23567. });
  23568. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23569. get: function () {
  23570. return this._ignore;
  23571. },
  23572. set: function (b) {
  23573. this._ignore = b;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. return ClickInfo;
  23579. }());
  23580. /**
  23581. * This class is used by the onRenderingGroupObservable
  23582. */
  23583. var RenderingGroupInfo = /** @class */ (function () {
  23584. function RenderingGroupInfo() {
  23585. }
  23586. /**
  23587. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23588. * This stage will be fired no matter what
  23589. */
  23590. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23591. /**
  23592. * Called before opaque object are rendered.
  23593. * This stage will be fired only if there's 3D Opaque content to render
  23594. */
  23595. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23596. /**
  23597. * Called after the opaque objects are rendered and before the transparent ones
  23598. * This stage will be fired only if there's 3D transparent content to render
  23599. */
  23600. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23601. /**
  23602. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23603. * This stage will be fired no matter what
  23604. */
  23605. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23606. return RenderingGroupInfo;
  23607. }());
  23608. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23609. /**
  23610. * Represents a scene to be rendered by the engine.
  23611. * @see http://doc.babylonjs.com/features/scene
  23612. */
  23613. var Scene = /** @class */ (function () {
  23614. /**
  23615. * Creates a new Scene
  23616. * @param engine defines the engine to use to render this scene
  23617. */
  23618. function Scene(engine) {
  23619. // Members
  23620. /**
  23621. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23622. */
  23623. this.autoClear = true;
  23624. /**
  23625. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23626. */
  23627. this.autoClearDepthAndStencil = true;
  23628. /**
  23629. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23630. */
  23631. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23632. /**
  23633. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23634. */
  23635. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23636. this._forceWireframe = false;
  23637. this._forcePointsCloud = false;
  23638. /**
  23639. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23640. */
  23641. this.forceShowBoundingBoxes = false;
  23642. /**
  23643. * Gets or sets a boolean indicating if animations are enabled
  23644. */
  23645. this.animationsEnabled = true;
  23646. this._animationPropertiesOverride = null;
  23647. /**
  23648. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23649. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23650. */
  23651. this.useConstantAnimationDeltaTime = false;
  23652. /**
  23653. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23654. * Please note that it requires to run a ray cast through the scene on every frame
  23655. */
  23656. this.constantlyUpdateMeshUnderPointer = false;
  23657. /**
  23658. * Defines the HTML cursor to use when hovering over interactive elements
  23659. */
  23660. this.hoverCursor = "pointer";
  23661. /**
  23662. * Defines the HTML default cursor to use (empty by default)
  23663. */
  23664. this.defaultCursor = "";
  23665. /**
  23666. * This is used to call preventDefault() on pointer down
  23667. * in order to block unwanted artifacts like system double clicks
  23668. */
  23669. this.preventDefaultOnPointerDown = true;
  23670. // Metadata
  23671. /**
  23672. * Gets or sets user defined metadata
  23673. */
  23674. this.metadata = null;
  23675. /**
  23676. * Use this array to add regular expressions used to disable offline support for specific urls
  23677. */
  23678. this.disableOfflineSupportExceptionRules = new Array();
  23679. /**
  23680. * An event triggered when the scene is disposed.
  23681. */
  23682. this.onDisposeObservable = new BABYLON.Observable();
  23683. this._onDisposeObserver = null;
  23684. /**
  23685. * An event triggered before rendering the scene (right after animations and physics)
  23686. */
  23687. this.onBeforeRenderObservable = new BABYLON.Observable();
  23688. this._onBeforeRenderObserver = null;
  23689. /**
  23690. * An event triggered after rendering the scene
  23691. */
  23692. this.onAfterRenderObservable = new BABYLON.Observable();
  23693. this._onAfterRenderObserver = null;
  23694. /**
  23695. * An event triggered before animating the scene
  23696. */
  23697. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered after animations processing
  23700. */
  23701. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered before draw calls are ready to be sent
  23704. */
  23705. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered after draw calls have been sent
  23708. */
  23709. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23710. /**
  23711. * An event triggered when physic simulation is about to be run
  23712. */
  23713. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered when physic simulation has been done
  23716. */
  23717. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered when the scene is ready
  23720. */
  23721. this.onReadyObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered before rendering a camera
  23724. */
  23725. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23726. this._onBeforeCameraRenderObserver = null;
  23727. /**
  23728. * An event triggered after rendering a camera
  23729. */
  23730. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23731. this._onAfterCameraRenderObserver = null;
  23732. /**
  23733. * An event triggered when active meshes evaluation is about to start
  23734. */
  23735. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23736. /**
  23737. * An event triggered when active meshes evaluation is done
  23738. */
  23739. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when particles rendering is about to start
  23742. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23743. */
  23744. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23745. /**
  23746. * An event triggered when particles rendering is done
  23747. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23748. */
  23749. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23750. /**
  23751. * An event triggered when sprites rendering is about to start
  23752. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23753. */
  23754. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23755. /**
  23756. * An event triggered when sprites rendering is done
  23757. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23758. */
  23759. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23762. */
  23763. this.onDataLoadedObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered when a camera is created
  23766. */
  23767. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23768. /**
  23769. * An event triggered when a camera is removed
  23770. */
  23771. this.onCameraRemovedObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered when a light is created
  23774. */
  23775. this.onNewLightAddedObservable = new BABYLON.Observable();
  23776. /**
  23777. * An event triggered when a light is removed
  23778. */
  23779. this.onLightRemovedObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when a geometry is created
  23782. */
  23783. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when a geometry is removed
  23786. */
  23787. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when a transform node is created
  23790. */
  23791. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when a transform node is removed
  23794. */
  23795. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23796. /**
  23797. * An event triggered when a mesh is created
  23798. */
  23799. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when a mesh is removed
  23802. */
  23803. this.onMeshRemovedObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when render targets are about to be rendered
  23806. * Can happen multiple times per frame.
  23807. */
  23808. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23809. /**
  23810. * An event triggered when render targets were rendered.
  23811. * Can happen multiple times per frame.
  23812. */
  23813. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23814. /**
  23815. * An event triggered before calculating deterministic simulation step
  23816. */
  23817. this.onBeforeStepObservable = new BABYLON.Observable();
  23818. /**
  23819. * An event triggered after calculating deterministic simulation step
  23820. */
  23821. this.onAfterStepObservable = new BABYLON.Observable();
  23822. /**
  23823. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23824. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23825. * 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)
  23826. */
  23827. this.onRenderingGroupObservable = new BABYLON.Observable();
  23828. // Animations
  23829. /**
  23830. * Gets a list of Animations associated with the scene
  23831. */
  23832. this.animations = [];
  23833. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23834. /**
  23835. * 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).
  23836. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23837. */
  23838. this.onPrePointerObservable = new BABYLON.Observable();
  23839. /**
  23840. * Observable event triggered each time an input event is received from the rendering canvas
  23841. */
  23842. this.onPointerObservable = new BABYLON.Observable();
  23843. this._meshPickProceed = false;
  23844. this._currentPickResult = null;
  23845. this._previousPickResult = null;
  23846. this._totalPointersPressed = 0;
  23847. this._doubleClickOccured = false;
  23848. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23849. this.cameraToUseForPointers = null;
  23850. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23851. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23852. this._startingPointerTime = 0;
  23853. this._previousStartingPointerTime = 0;
  23854. this._pointerCaptures = {};
  23855. // Deterministic lockstep
  23856. this._timeAccumulator = 0;
  23857. this._currentStepId = 0;
  23858. this._currentInternalStep = 0;
  23859. // Keyboard
  23860. /**
  23861. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23862. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23863. */
  23864. this.onPreKeyboardObservable = new BABYLON.Observable();
  23865. /**
  23866. * Observable event triggered each time an keyboard event is received from the hosting window
  23867. */
  23868. this.onKeyboardObservable = new BABYLON.Observable();
  23869. // Coordinates system
  23870. this._useRightHandedSystem = false;
  23871. // Fog
  23872. this._fogEnabled = true;
  23873. this._fogMode = Scene.FOGMODE_NONE;
  23874. /**
  23875. * Gets or sets the fog color to use
  23876. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23877. */
  23878. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23879. /**
  23880. * Gets or sets the fog density to use
  23881. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23882. */
  23883. this.fogDensity = 0.1;
  23884. /**
  23885. * Gets or sets the fog start distance to use
  23886. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23887. */
  23888. this.fogStart = 0;
  23889. /**
  23890. * Gets or sets the fog end distance to use
  23891. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23892. */
  23893. this.fogEnd = 1000.0;
  23894. // Lights
  23895. this._shadowsEnabled = true;
  23896. this._lightsEnabled = true;
  23897. /**
  23898. * All of the lights added to this scene
  23899. * @see http://doc.babylonjs.com/babylon101/lights
  23900. */
  23901. this.lights = new Array();
  23902. // Cameras
  23903. /** All of the cameras added to this scene.
  23904. * @see http://doc.babylonjs.com/babylon101/cameras
  23905. */
  23906. this.cameras = new Array();
  23907. /** All of the active cameras added to this scene. */
  23908. this.activeCameras = new Array();
  23909. // Meshes
  23910. /**
  23911. * All of the tranform nodes added to this scene
  23912. * @see http://doc.babylonjs.com/how_to/transformnode
  23913. */
  23914. this.transformNodes = new Array();
  23915. /**
  23916. * All of the (abstract) meshes added to this scene
  23917. */
  23918. this.meshes = new Array();
  23919. /**
  23920. * All of the animation groups added to this scene
  23921. * @see http://doc.babylonjs.com/how_to/group
  23922. */
  23923. this.animationGroups = new Array();
  23924. // Geometries
  23925. this._geometries = new Array();
  23926. /**
  23927. * All of the materials added to this scene
  23928. * @see http://doc.babylonjs.com/babylon101/materials
  23929. */
  23930. this.materials = new Array();
  23931. /**
  23932. * All of the multi-materials added to this scene
  23933. * @see http://doc.babylonjs.com/how_to/multi_materials
  23934. */
  23935. this.multiMaterials = new Array();
  23936. // Textures
  23937. this._texturesEnabled = true;
  23938. /**
  23939. * All of the textures added to this scene
  23940. */
  23941. this.textures = new Array();
  23942. // Particles
  23943. /**
  23944. * Gets or sets a boolean indicating if particles are enabled on this scene
  23945. */
  23946. this.particlesEnabled = true;
  23947. /**
  23948. * All of the particle systems added to this scene
  23949. * @see http://doc.babylonjs.com/babylon101/particles
  23950. */
  23951. this.particleSystems = new Array();
  23952. // Sprites
  23953. /**
  23954. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23955. */
  23956. this.spritesEnabled = true;
  23957. /**
  23958. * All of the sprite managers added to this scene
  23959. * @see http://doc.babylonjs.com/babylon101/sprites
  23960. */
  23961. this.spriteManagers = new Array();
  23962. /**
  23963. * The list of layers (background and foreground) of the scene
  23964. */
  23965. this.layers = new Array();
  23966. /**
  23967. * The list of effect layers (highlights/glow) added to the scene
  23968. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23969. * @see http://doc.babylonjs.com/how_to/glow_layer
  23970. */
  23971. this.effectLayers = new Array();
  23972. // Skeletons
  23973. this._skeletonsEnabled = true;
  23974. /**
  23975. * The list of skeletons added to the scene
  23976. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23977. */
  23978. this.skeletons = new Array();
  23979. // Morph targets
  23980. /**
  23981. * The list of morph target managers added to the scene
  23982. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23983. */
  23984. this.morphTargetManagers = new Array();
  23985. // Lens flares
  23986. /**
  23987. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23988. */
  23989. this.lensFlaresEnabled = true;
  23990. /**
  23991. * The list of lens flare system added to the scene
  23992. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23993. */
  23994. this.lensFlareSystems = new Array();
  23995. // Collisions
  23996. /**
  23997. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23998. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23999. */
  24000. this.collisionsEnabled = true;
  24001. /**
  24002. * Defines the gravity applied to this scene (used only for collisions)
  24003. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24004. */
  24005. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24006. // Postprocesses
  24007. /**
  24008. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24009. */
  24010. this.postProcessesEnabled = true;
  24011. /**
  24012. * The list of postprocesses added to the scene
  24013. */
  24014. this.postProcesses = new Array();
  24015. // Customs render targets
  24016. /**
  24017. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24018. */
  24019. this.renderTargetsEnabled = true;
  24020. /**
  24021. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24022. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24023. */
  24024. this.dumpNextRenderTargets = false;
  24025. /**
  24026. * The list of user defined render targets added to the scene
  24027. */
  24028. this.customRenderTargets = new Array();
  24029. /**
  24030. * Gets the list of meshes imported to the scene through SceneLoader
  24031. */
  24032. this.importedMeshesFiles = new Array();
  24033. // Probes
  24034. /**
  24035. * Gets or sets a boolean indicating if probes are enabled on this scene
  24036. */
  24037. this.probesEnabled = true;
  24038. /**
  24039. * The list of reflection probes added to the scene
  24040. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24041. */
  24042. this.reflectionProbes = new Array();
  24043. /** @hidden */
  24044. this._actionManagers = new Array();
  24045. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24046. // Procedural textures
  24047. /**
  24048. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24049. */
  24050. this.proceduralTexturesEnabled = true;
  24051. /**
  24052. * The list of procedural textures added to the scene
  24053. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24054. */
  24055. this.proceduralTextures = new Array();
  24056. /**
  24057. * The list of sound tracks added to the scene
  24058. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24059. */
  24060. this.soundTracks = new Array();
  24061. this._audioEnabled = true;
  24062. this._headphone = false;
  24063. // Performance counters
  24064. this._totalVertices = new BABYLON.PerfCounter();
  24065. /** @hidden */
  24066. this._activeIndices = new BABYLON.PerfCounter();
  24067. /** @hidden */
  24068. this._activeParticles = new BABYLON.PerfCounter();
  24069. /** @hidden */
  24070. this._activeBones = new BABYLON.PerfCounter();
  24071. this._animationTime = 0;
  24072. /**
  24073. * Gets or sets a general scale for animation speed
  24074. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24075. */
  24076. this.animationTimeScale = 1;
  24077. this._renderId = 0;
  24078. this._executeWhenReadyTimeoutId = -1;
  24079. this._intermediateRendering = false;
  24080. this._viewUpdateFlag = -1;
  24081. this._projectionUpdateFlag = -1;
  24082. this._alternateViewUpdateFlag = -1;
  24083. this._alternateProjectionUpdateFlag = -1;
  24084. /** @hidden */
  24085. this._toBeDisposed = new BABYLON.SmartArray(256);
  24086. this._activeRequests = new Array();
  24087. this._pendingData = new Array();
  24088. this._isDisposed = false;
  24089. /**
  24090. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24091. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24092. */
  24093. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24094. this._activeMeshes = new BABYLON.SmartArray(256);
  24095. this._processedMaterials = new BABYLON.SmartArray(256);
  24096. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24097. /** @hidden */
  24098. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24099. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24100. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24101. /** @hidden */
  24102. this._activeAnimatables = new Array();
  24103. this._transformMatrix = BABYLON.Matrix.Zero();
  24104. this._useAlternateCameraConfiguration = false;
  24105. this._alternateRendering = false;
  24106. /**
  24107. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24108. * This is useful if there are more lights that the maximum simulteanous authorized
  24109. */
  24110. this.requireLightSorting = false;
  24111. this._depthRenderer = {};
  24112. this._activeMeshesFrozen = false;
  24113. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24114. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24115. this._engine.scenes.push(this);
  24116. this._uid = null;
  24117. this._renderingManager = new BABYLON.RenderingManager(this);
  24118. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24119. if (BABYLON.OutlineRenderer) {
  24120. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24121. }
  24122. if (BABYLON.Tools.IsWindowObjectExist()) {
  24123. this.attachControl();
  24124. }
  24125. //simplification queue
  24126. if (BABYLON.SimplificationQueue) {
  24127. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24128. }
  24129. //collision coordinator initialization. For now legacy per default.
  24130. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24131. // Uniform Buffer
  24132. this._createUbo();
  24133. // Default Image processing definition.
  24134. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24135. }
  24136. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24137. /** The fog is deactivated */
  24138. get: function () {
  24139. return Scene._FOGMODE_NONE;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24145. /** The fog density is following an exponential function */
  24146. get: function () {
  24147. return Scene._FOGMODE_EXP;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24153. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24154. get: function () {
  24155. return Scene._FOGMODE_EXP2;
  24156. },
  24157. enumerable: true,
  24158. configurable: true
  24159. });
  24160. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24161. /** The fog density is following a linear function. */
  24162. get: function () {
  24163. return Scene._FOGMODE_LINEAR;
  24164. },
  24165. enumerable: true,
  24166. configurable: true
  24167. });
  24168. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24169. /**
  24170. * Texture used in all pbr material as the reflection texture.
  24171. * As in the majority of the scene they are the same (exception for multi room and so on),
  24172. * this is easier to reference from here than from all the materials.
  24173. */
  24174. get: function () {
  24175. return this._environmentTexture;
  24176. },
  24177. /**
  24178. * Texture used in all pbr material as the reflection texture.
  24179. * As in the majority of the scene they are the same (exception for multi room and so on),
  24180. * this is easier to set here than in all the materials.
  24181. */
  24182. set: function (value) {
  24183. if (this._environmentTexture === value) {
  24184. return;
  24185. }
  24186. this._environmentTexture = value;
  24187. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24188. },
  24189. enumerable: true,
  24190. configurable: true
  24191. });
  24192. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24193. /**
  24194. * Default image processing configuration used either in the rendering
  24195. * Forward main pass or through the imageProcessingPostProcess if present.
  24196. * As in the majority of the scene they are the same (exception for multi camera),
  24197. * this is easier to reference from here than from all the materials and post process.
  24198. *
  24199. * No setter as we it is a shared configuration, you can set the values instead.
  24200. */
  24201. get: function () {
  24202. return this._imageProcessingConfiguration;
  24203. },
  24204. enumerable: true,
  24205. configurable: true
  24206. });
  24207. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24208. get: function () {
  24209. return this._forceWireframe;
  24210. },
  24211. /**
  24212. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24213. */
  24214. set: function (value) {
  24215. if (this._forceWireframe === value) {
  24216. return;
  24217. }
  24218. this._forceWireframe = value;
  24219. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24220. },
  24221. enumerable: true,
  24222. configurable: true
  24223. });
  24224. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24225. get: function () {
  24226. return this._forcePointsCloud;
  24227. },
  24228. /**
  24229. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24230. */
  24231. set: function (value) {
  24232. if (this._forcePointsCloud === value) {
  24233. return;
  24234. }
  24235. this._forcePointsCloud = value;
  24236. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24237. },
  24238. enumerable: true,
  24239. configurable: true
  24240. });
  24241. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24242. /**
  24243. * Gets or sets the animation properties override
  24244. */
  24245. get: function () {
  24246. return this._animationPropertiesOverride;
  24247. },
  24248. set: function (value) {
  24249. this._animationPropertiesOverride = value;
  24250. },
  24251. enumerable: true,
  24252. configurable: true
  24253. });
  24254. Object.defineProperty(Scene.prototype, "onDispose", {
  24255. /** Sets a function to be executed when this scene is disposed. */
  24256. set: function (callback) {
  24257. if (this._onDisposeObserver) {
  24258. this.onDisposeObservable.remove(this._onDisposeObserver);
  24259. }
  24260. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24261. },
  24262. enumerable: true,
  24263. configurable: true
  24264. });
  24265. Object.defineProperty(Scene.prototype, "beforeRender", {
  24266. /** Sets a function to be executed before rendering this scene */
  24267. set: function (callback) {
  24268. if (this._onBeforeRenderObserver) {
  24269. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24270. }
  24271. if (callback) {
  24272. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24273. }
  24274. },
  24275. enumerable: true,
  24276. configurable: true
  24277. });
  24278. Object.defineProperty(Scene.prototype, "afterRender", {
  24279. /** Sets a function to be executed after rendering this scene */
  24280. set: function (callback) {
  24281. if (this._onAfterRenderObserver) {
  24282. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24283. }
  24284. if (callback) {
  24285. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24286. }
  24287. },
  24288. enumerable: true,
  24289. configurable: true
  24290. });
  24291. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24292. /** Sets a function to be executed before rendering a camera*/
  24293. set: function (callback) {
  24294. if (this._onBeforeCameraRenderObserver) {
  24295. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24296. }
  24297. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24298. },
  24299. enumerable: true,
  24300. configurable: true
  24301. });
  24302. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24303. /** Sets a function to be executed after rendering a camera*/
  24304. set: function (callback) {
  24305. if (this._onAfterCameraRenderObserver) {
  24306. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24307. }
  24308. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24309. },
  24310. enumerable: true,
  24311. configurable: true
  24312. });
  24313. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24314. /**
  24315. * Gets the gamepad manager associated with the scene
  24316. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24317. */
  24318. get: function () {
  24319. if (!this._gamepadManager) {
  24320. this._gamepadManager = new BABYLON.GamepadManager(this);
  24321. }
  24322. return this._gamepadManager;
  24323. },
  24324. enumerable: true,
  24325. configurable: true
  24326. });
  24327. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24328. /**
  24329. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24330. */
  24331. get: function () {
  24332. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24338. get: function () {
  24339. return this._useRightHandedSystem;
  24340. },
  24341. /**
  24342. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24343. */
  24344. set: function (value) {
  24345. if (this._useRightHandedSystem === value) {
  24346. return;
  24347. }
  24348. this._useRightHandedSystem = value;
  24349. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24350. },
  24351. enumerable: true,
  24352. configurable: true
  24353. });
  24354. /**
  24355. * Sets the step Id used by deterministic lock step
  24356. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24357. * @param newStepId defines the step Id
  24358. */
  24359. Scene.prototype.setStepId = function (newStepId) {
  24360. this._currentStepId = newStepId;
  24361. };
  24362. ;
  24363. /**
  24364. * Gets the step Id used by deterministic lock step
  24365. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24366. * @returns the step Id
  24367. */
  24368. Scene.prototype.getStepId = function () {
  24369. return this._currentStepId;
  24370. };
  24371. ;
  24372. /**
  24373. * Gets the internal step used by deterministic lock step
  24374. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24375. * @returns the internal step
  24376. */
  24377. Scene.prototype.getInternalStep = function () {
  24378. return this._currentInternalStep;
  24379. };
  24380. ;
  24381. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24382. get: function () {
  24383. return this._fogEnabled;
  24384. },
  24385. /**
  24386. * Gets or sets a boolean indicating if fog is enabled on this scene
  24387. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24388. */
  24389. set: function (value) {
  24390. if (this._fogEnabled === value) {
  24391. return;
  24392. }
  24393. this._fogEnabled = value;
  24394. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24395. },
  24396. enumerable: true,
  24397. configurable: true
  24398. });
  24399. Object.defineProperty(Scene.prototype, "fogMode", {
  24400. get: function () {
  24401. return this._fogMode;
  24402. },
  24403. /**
  24404. * Gets or sets the fog mode to use
  24405. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24406. */
  24407. set: function (value) {
  24408. if (this._fogMode === value) {
  24409. return;
  24410. }
  24411. this._fogMode = value;
  24412. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24413. },
  24414. enumerable: true,
  24415. configurable: true
  24416. });
  24417. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24418. get: function () {
  24419. return this._shadowsEnabled;
  24420. },
  24421. /**
  24422. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24423. */
  24424. set: function (value) {
  24425. if (this._shadowsEnabled === value) {
  24426. return;
  24427. }
  24428. this._shadowsEnabled = value;
  24429. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24435. get: function () {
  24436. return this._lightsEnabled;
  24437. },
  24438. /**
  24439. * Gets or sets a boolean indicating if lights are enabled on this scene
  24440. */
  24441. set: function (value) {
  24442. if (this._lightsEnabled === value) {
  24443. return;
  24444. }
  24445. this._lightsEnabled = value;
  24446. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24452. /** The default material used on meshes when no material is affected */
  24453. get: function () {
  24454. if (!this._defaultMaterial) {
  24455. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24456. }
  24457. return this._defaultMaterial;
  24458. },
  24459. /** The default material used on meshes when no material is affected */
  24460. set: function (value) {
  24461. this._defaultMaterial = value;
  24462. },
  24463. enumerable: true,
  24464. configurable: true
  24465. });
  24466. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24467. get: function () {
  24468. return this._texturesEnabled;
  24469. },
  24470. /**
  24471. * Gets or sets a boolean indicating if textures are enabled on this scene
  24472. */
  24473. set: function (value) {
  24474. if (this._texturesEnabled === value) {
  24475. return;
  24476. }
  24477. this._texturesEnabled = value;
  24478. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24479. },
  24480. enumerable: true,
  24481. configurable: true
  24482. });
  24483. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24484. get: function () {
  24485. return this._skeletonsEnabled;
  24486. },
  24487. /**
  24488. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24489. */
  24490. set: function (value) {
  24491. if (this._skeletonsEnabled === value) {
  24492. return;
  24493. }
  24494. this._skeletonsEnabled = value;
  24495. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24496. },
  24497. enumerable: true,
  24498. configurable: true
  24499. });
  24500. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24501. /**
  24502. * Gets the postprocess render pipeline manager
  24503. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24504. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24505. */
  24506. get: function () {
  24507. if (!this._postProcessRenderPipelineManager) {
  24508. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24509. }
  24510. return this._postProcessRenderPipelineManager;
  24511. },
  24512. enumerable: true,
  24513. configurable: true
  24514. });
  24515. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24516. /**
  24517. * Gets the main soundtrack associated with the scene
  24518. */
  24519. get: function () {
  24520. if (!this._mainSoundTrack) {
  24521. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24522. }
  24523. return this._mainSoundTrack;
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24529. /** @hidden */
  24530. get: function () {
  24531. return this._alternateRendering;
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24537. /**
  24538. * Gets the list of frustum planes (built from the active camera)
  24539. */
  24540. get: function () {
  24541. return this._frustumPlanes;
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24547. /**
  24548. * Gets the current geometry buffer associated to the scene.
  24549. */
  24550. get: function () {
  24551. return this._geometryBufferRenderer;
  24552. },
  24553. /**
  24554. * Sets the current geometry buffer for the scene.
  24555. */
  24556. set: function (geometryBufferRenderer) {
  24557. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24558. this._geometryBufferRenderer = geometryBufferRenderer;
  24559. }
  24560. },
  24561. enumerable: true,
  24562. configurable: true
  24563. });
  24564. Object.defineProperty(Scene.prototype, "debugLayer", {
  24565. /**
  24566. * Gets the debug layer associated with the scene
  24567. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24568. */
  24569. get: function () {
  24570. if (!this._debugLayer) {
  24571. this._debugLayer = new BABYLON.DebugLayer(this);
  24572. }
  24573. return this._debugLayer;
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24579. /**
  24580. * Gets a boolean indicating if collisions are processed on a web worker
  24581. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24582. */
  24583. get: function () {
  24584. return this._workerCollisions;
  24585. },
  24586. set: function (enabled) {
  24587. if (!BABYLON.CollisionCoordinatorLegacy) {
  24588. return;
  24589. }
  24590. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24591. this._workerCollisions = enabled;
  24592. if (this.collisionCoordinator) {
  24593. this.collisionCoordinator.destroy();
  24594. }
  24595. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24596. this.collisionCoordinator.init(this);
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24602. /**
  24603. * Gets the octree used to boost mesh selection (picking)
  24604. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24605. */
  24606. get: function () {
  24607. return this._selectionOctree;
  24608. },
  24609. enumerable: true,
  24610. configurable: true
  24611. });
  24612. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24613. /**
  24614. * Gets the mesh that is currently under the pointer
  24615. */
  24616. get: function () {
  24617. return this._pointerOverMesh;
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Object.defineProperty(Scene.prototype, "pointerX", {
  24623. /**
  24624. * Gets the current on-screen X position of the pointer
  24625. */
  24626. get: function () {
  24627. return this._pointerX;
  24628. },
  24629. enumerable: true,
  24630. configurable: true
  24631. });
  24632. Object.defineProperty(Scene.prototype, "pointerY", {
  24633. /**
  24634. * Gets the current on-screen Y position of the pointer
  24635. */
  24636. get: function () {
  24637. return this._pointerY;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. /**
  24643. * Gets the cached material (ie. the latest rendered one)
  24644. * @returns the cached material
  24645. */
  24646. Scene.prototype.getCachedMaterial = function () {
  24647. return this._cachedMaterial;
  24648. };
  24649. /**
  24650. * Gets the cached effect (ie. the latest rendered one)
  24651. * @returns the cached effect
  24652. */
  24653. Scene.prototype.getCachedEffect = function () {
  24654. return this._cachedEffect;
  24655. };
  24656. /**
  24657. * Gets the cached visibility state (ie. the latest rendered one)
  24658. * @returns the cached visibility state
  24659. */
  24660. Scene.prototype.getCachedVisibility = function () {
  24661. return this._cachedVisibility;
  24662. };
  24663. /**
  24664. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24665. * @param material defines the current material
  24666. * @param effect defines the current effect
  24667. * @param visibility defines the current visibility state
  24668. * @returns true if one parameter is not cached
  24669. */
  24670. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24671. if (visibility === void 0) { visibility = 1; }
  24672. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24673. };
  24674. /**
  24675. * Gets the bounding box renderer associated with the scene
  24676. * @returns a BoundingBoxRenderer
  24677. */
  24678. Scene.prototype.getBoundingBoxRenderer = function () {
  24679. if (!this._boundingBoxRenderer) {
  24680. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24681. }
  24682. return this._boundingBoxRenderer;
  24683. };
  24684. /**
  24685. * Gets the outline renderer associated with the scene
  24686. * @returns a OutlineRenderer
  24687. */
  24688. Scene.prototype.getOutlineRenderer = function () {
  24689. return this._outlineRenderer;
  24690. };
  24691. /**
  24692. * Gets the engine associated with the scene
  24693. * @returns an Engine
  24694. */
  24695. Scene.prototype.getEngine = function () {
  24696. return this._engine;
  24697. };
  24698. /**
  24699. * Gets the total number of vertices rendered per frame
  24700. * @returns the total number of vertices rendered per frame
  24701. */
  24702. Scene.prototype.getTotalVertices = function () {
  24703. return this._totalVertices.current;
  24704. };
  24705. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24706. /**
  24707. * Gets the performance counter for total vertices
  24708. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24709. */
  24710. get: function () {
  24711. return this._totalVertices;
  24712. },
  24713. enumerable: true,
  24714. configurable: true
  24715. });
  24716. /**
  24717. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24718. * @returns the total number of active indices rendered per frame
  24719. */
  24720. Scene.prototype.getActiveIndices = function () {
  24721. return this._activeIndices.current;
  24722. };
  24723. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24724. /**
  24725. * Gets the performance counter for active indices
  24726. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24727. */
  24728. get: function () {
  24729. return this._activeIndices;
  24730. },
  24731. enumerable: true,
  24732. configurable: true
  24733. });
  24734. /**
  24735. * Gets the total number of active particles rendered per frame
  24736. * @returns the total number of active particles rendered per frame
  24737. */
  24738. Scene.prototype.getActiveParticles = function () {
  24739. return this._activeParticles.current;
  24740. };
  24741. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24742. /**
  24743. * Gets the performance counter for active particles
  24744. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24745. */
  24746. get: function () {
  24747. return this._activeParticles;
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. /**
  24753. * Gets the total number of active bones rendered per frame
  24754. * @returns the total number of active bones rendered per frame
  24755. */
  24756. Scene.prototype.getActiveBones = function () {
  24757. return this._activeBones.current;
  24758. };
  24759. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24760. /**
  24761. * Gets the performance counter for active bones
  24762. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24763. */
  24764. get: function () {
  24765. return this._activeBones;
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. /** @hidden */
  24771. Scene.prototype.getInterFramePerfCounter = function () {
  24772. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24773. return 0;
  24774. };
  24775. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24776. /** @hidden */
  24777. get: function () {
  24778. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24779. return null;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. /** @hidden */
  24785. Scene.prototype.getLastFrameDuration = function () {
  24786. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24787. return 0;
  24788. };
  24789. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24790. /** @hidden */
  24791. get: function () {
  24792. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24793. return null;
  24794. },
  24795. enumerable: true,
  24796. configurable: true
  24797. });
  24798. /** @hidden */
  24799. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24800. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24801. return 0;
  24802. };
  24803. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24804. /** @hidden */
  24805. get: function () {
  24806. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24807. return null;
  24808. },
  24809. enumerable: true,
  24810. configurable: true
  24811. });
  24812. /**
  24813. * Gets the array of active meshes
  24814. * @returns an array of AbstractMesh
  24815. */
  24816. Scene.prototype.getActiveMeshes = function () {
  24817. return this._activeMeshes;
  24818. };
  24819. /** @hidden */
  24820. Scene.prototype.getRenderTargetsDuration = function () {
  24821. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24822. return 0;
  24823. };
  24824. /** @hidden */
  24825. Scene.prototype.getRenderDuration = function () {
  24826. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24827. return 0;
  24828. };
  24829. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24830. /** @hidden */
  24831. get: function () {
  24832. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24833. return null;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. /** @hidden */
  24839. Scene.prototype.getParticlesDuration = function () {
  24840. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24841. return 0;
  24842. };
  24843. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24844. /** @hidden */
  24845. get: function () {
  24846. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24847. return null;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. /** @hidden */
  24853. Scene.prototype.getSpritesDuration = function () {
  24854. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24855. return 0;
  24856. };
  24857. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24858. /** @hidden */
  24859. get: function () {
  24860. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24861. return null;
  24862. },
  24863. enumerable: true,
  24864. configurable: true
  24865. });
  24866. /**
  24867. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24868. * @returns a number
  24869. */
  24870. Scene.prototype.getAnimationRatio = function () {
  24871. return this._animationRatio;
  24872. };
  24873. /**
  24874. * Gets an unique Id for the current frame
  24875. * @returns a number
  24876. */
  24877. Scene.prototype.getRenderId = function () {
  24878. return this._renderId;
  24879. };
  24880. /** Call this function if you want to manually increment the render Id*/
  24881. Scene.prototype.incrementRenderId = function () {
  24882. this._renderId++;
  24883. };
  24884. Scene.prototype._updatePointerPosition = function (evt) {
  24885. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24886. if (!canvasRect) {
  24887. return;
  24888. }
  24889. this._pointerX = evt.clientX - canvasRect.left;
  24890. this._pointerY = evt.clientY - canvasRect.top;
  24891. this._unTranslatedPointerX = this._pointerX;
  24892. this._unTranslatedPointerY = this._pointerY;
  24893. };
  24894. Scene.prototype._createUbo = function () {
  24895. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24896. this._sceneUbo.addUniform("viewProjection", 16);
  24897. this._sceneUbo.addUniform("view", 16);
  24898. };
  24899. Scene.prototype._createAlternateUbo = function () {
  24900. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24901. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24902. this._alternateSceneUbo.addUniform("view", 16);
  24903. };
  24904. // Pointers handling
  24905. /**
  24906. * Use this method to simulate a pointer move on a mesh
  24907. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24908. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24909. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24910. * @returns the current scene
  24911. */
  24912. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24913. var evt = new PointerEvent("pointermove", pointerEventInit);
  24914. return this._processPointerMove(pickResult, evt);
  24915. };
  24916. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24917. var canvas = this._engine.getRenderingCanvas();
  24918. if (!canvas) {
  24919. return this;
  24920. }
  24921. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24922. this.setPointerOverSprite(null);
  24923. this.setPointerOverMesh(pickResult.pickedMesh);
  24924. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24925. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24926. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24927. }
  24928. else {
  24929. canvas.style.cursor = this.hoverCursor;
  24930. }
  24931. }
  24932. else {
  24933. canvas.style.cursor = this.defaultCursor;
  24934. }
  24935. }
  24936. else {
  24937. this.setPointerOverMesh(null);
  24938. // Sprites
  24939. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24940. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24941. this.setPointerOverSprite(pickResult.pickedSprite);
  24942. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24943. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24944. }
  24945. else {
  24946. canvas.style.cursor = this.hoverCursor;
  24947. }
  24948. }
  24949. else {
  24950. this.setPointerOverSprite(null);
  24951. // Restore pointer
  24952. canvas.style.cursor = this.defaultCursor;
  24953. }
  24954. }
  24955. if (pickResult) {
  24956. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24957. if (this.onPointerMove) {
  24958. this.onPointerMove(evt, pickResult, type);
  24959. }
  24960. if (this.onPointerObservable.hasObservers()) {
  24961. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24962. this.onPointerObservable.notifyObservers(pi, type);
  24963. }
  24964. }
  24965. return this;
  24966. };
  24967. /**
  24968. * Use this method to simulate a pointer down on a mesh
  24969. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24970. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24971. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24972. * @returns the current scene
  24973. */
  24974. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24975. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24976. return this._processPointerDown(pickResult, evt);
  24977. };
  24978. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24979. var _this = this;
  24980. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24981. this._pickedDownMesh = pickResult.pickedMesh;
  24982. var actionManager = pickResult.pickedMesh.actionManager;
  24983. if (actionManager) {
  24984. if (actionManager.hasPickTriggers) {
  24985. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24986. switch (evt.button) {
  24987. case 0:
  24988. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24989. break;
  24990. case 1:
  24991. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24992. break;
  24993. case 2:
  24994. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24995. break;
  24996. }
  24997. }
  24998. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24999. window.setTimeout(function () {
  25000. 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);
  25001. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25002. if (_this._totalPointersPressed !== 0 &&
  25003. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25004. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25005. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25006. _this._startingPointerTime = 0;
  25007. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25008. }
  25009. }
  25010. }, Scene.LongPressDelay);
  25011. }
  25012. }
  25013. }
  25014. if (pickResult) {
  25015. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25016. if (this.onPointerDown) {
  25017. this.onPointerDown(evt, pickResult, type);
  25018. }
  25019. if (this.onPointerObservable.hasObservers()) {
  25020. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25021. this.onPointerObservable.notifyObservers(pi, type);
  25022. }
  25023. }
  25024. return this;
  25025. };
  25026. /**
  25027. * Use this method to simulate a pointer up on a mesh
  25028. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25029. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25030. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25031. * @returns the current scene
  25032. */
  25033. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25034. var evt = new PointerEvent("pointerup", pointerEventInit);
  25035. var clickInfo = new ClickInfo();
  25036. clickInfo.singleClick = true;
  25037. clickInfo.ignore = true;
  25038. return this._processPointerUp(pickResult, evt, clickInfo);
  25039. };
  25040. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25041. if (pickResult && pickResult && pickResult.pickedMesh) {
  25042. this._pickedUpMesh = pickResult.pickedMesh;
  25043. if (this._pickedDownMesh === this._pickedUpMesh) {
  25044. if (this.onPointerPick) {
  25045. this.onPointerPick(evt, pickResult);
  25046. }
  25047. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25048. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25049. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25050. this.onPointerObservable.notifyObservers(pi, type_1);
  25051. }
  25052. }
  25053. if (pickResult.pickedMesh.actionManager) {
  25054. if (clickInfo.ignore) {
  25055. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25056. }
  25057. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25058. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25059. }
  25060. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25061. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25062. }
  25063. }
  25064. }
  25065. if (this._pickedDownMesh &&
  25066. this._pickedDownMesh.actionManager &&
  25067. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25068. this._pickedDownMesh !== this._pickedUpMesh) {
  25069. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25070. }
  25071. var type = BABYLON.PointerEventTypes.POINTERUP;
  25072. if (this.onPointerObservable.hasObservers()) {
  25073. if (!clickInfo.ignore) {
  25074. if (!clickInfo.hasSwiped) {
  25075. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25076. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25077. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25078. this.onPointerObservable.notifyObservers(pi, type_2);
  25079. }
  25080. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25081. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25082. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25083. this.onPointerObservable.notifyObservers(pi, type_3);
  25084. }
  25085. }
  25086. }
  25087. else {
  25088. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25089. this.onPointerObservable.notifyObservers(pi, type);
  25090. }
  25091. }
  25092. if (this.onPointerUp) {
  25093. this.onPointerUp(evt, pickResult, type);
  25094. }
  25095. return this;
  25096. };
  25097. /**
  25098. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25099. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25100. * @returns true if the pointer was captured
  25101. */
  25102. Scene.prototype.isPointerCaptured = function (pointerId) {
  25103. if (pointerId === void 0) { pointerId = 0; }
  25104. return this._pointerCaptures[pointerId];
  25105. };
  25106. /**
  25107. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25108. * @param attachUp defines if you want to attach events to pointerup
  25109. * @param attachDown defines if you want to attach events to pointerdown
  25110. * @param attachMove defines if you want to attach events to pointermove
  25111. */
  25112. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25113. var _this = this;
  25114. if (attachUp === void 0) { attachUp = true; }
  25115. if (attachDown === void 0) { attachDown = true; }
  25116. if (attachMove === void 0) { attachMove = true; }
  25117. this._initActionManager = function (act, clickInfo) {
  25118. if (!_this._meshPickProceed) {
  25119. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25120. _this._currentPickResult = pickResult;
  25121. if (pickResult) {
  25122. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25123. }
  25124. _this._meshPickProceed = true;
  25125. }
  25126. return act;
  25127. };
  25128. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25129. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25130. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25131. btn !== _this._previousButtonPressed) {
  25132. _this._doubleClickOccured = false;
  25133. clickInfo.singleClick = true;
  25134. clickInfo.ignore = false;
  25135. cb(clickInfo, _this._currentPickResult);
  25136. }
  25137. };
  25138. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25139. var clickInfo = new ClickInfo();
  25140. _this._currentPickResult = null;
  25141. var act = null;
  25142. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25143. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25144. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25145. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25146. act = _this._initActionManager(act, clickInfo);
  25147. if (act)
  25148. checkPicking = act.hasPickTriggers;
  25149. }
  25150. if (checkPicking) {
  25151. var btn = evt.button;
  25152. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25153. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25154. if (!clickInfo.hasSwiped) {
  25155. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25156. if (!checkSingleClickImmediately) {
  25157. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25158. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25159. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25160. act = _this._initActionManager(act, clickInfo);
  25161. if (act)
  25162. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25163. }
  25164. }
  25165. if (checkSingleClickImmediately) {
  25166. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25167. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25168. btn !== _this._previousButtonPressed) {
  25169. clickInfo.singleClick = true;
  25170. cb(clickInfo, _this._currentPickResult);
  25171. }
  25172. }
  25173. // at least one double click is required to be check and exclusive double click is enabled
  25174. else {
  25175. // wait that no double click has been raised during the double click delay
  25176. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25177. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25178. }
  25179. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25180. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25181. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25182. act = _this._initActionManager(act, clickInfo);
  25183. if (act)
  25184. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25185. }
  25186. if (checkDoubleClick) {
  25187. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25188. if (btn === _this._previousButtonPressed &&
  25189. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25190. !_this._doubleClickOccured) {
  25191. // pointer has not moved for 2 clicks, it's a double click
  25192. if (!clickInfo.hasSwiped &&
  25193. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25194. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25195. _this._previousStartingPointerTime = 0;
  25196. _this._doubleClickOccured = true;
  25197. clickInfo.doubleClick = true;
  25198. clickInfo.ignore = false;
  25199. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25200. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25201. }
  25202. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25203. cb(clickInfo, _this._currentPickResult);
  25204. }
  25205. // if the two successive clicks are too far, it's just two simple clicks
  25206. else {
  25207. _this._doubleClickOccured = false;
  25208. _this._previousStartingPointerTime = _this._startingPointerTime;
  25209. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25210. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25211. _this._previousButtonPressed = btn;
  25212. if (Scene.ExclusiveDoubleClickMode) {
  25213. if (_this._previousDelayedSimpleClickTimeout) {
  25214. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25215. }
  25216. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25217. cb(clickInfo, _this._previousPickResult);
  25218. }
  25219. else {
  25220. cb(clickInfo, _this._currentPickResult);
  25221. }
  25222. }
  25223. }
  25224. // just the first click of the double has been raised
  25225. else {
  25226. _this._doubleClickOccured = false;
  25227. _this._previousStartingPointerTime = _this._startingPointerTime;
  25228. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25229. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25230. _this._previousButtonPressed = btn;
  25231. }
  25232. }
  25233. }
  25234. }
  25235. clickInfo.ignore = true;
  25236. cb(clickInfo, _this._currentPickResult);
  25237. };
  25238. this._spritePredicate = function (sprite) {
  25239. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25240. };
  25241. this._onPointerMove = function (evt) {
  25242. _this._updatePointerPosition(evt);
  25243. // PreObservable support
  25244. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25245. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25246. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25247. _this.onPrePointerObservable.notifyObservers(pi, type);
  25248. if (pi.skipOnPointerObservable) {
  25249. return;
  25250. }
  25251. }
  25252. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25253. return;
  25254. }
  25255. if (!_this.pointerMovePredicate) {
  25256. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25257. }
  25258. // Meshes
  25259. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25260. _this._processPointerMove(pickResult, evt);
  25261. };
  25262. this._onPointerDown = function (evt) {
  25263. _this._totalPointersPressed++;
  25264. _this._pickedDownMesh = null;
  25265. _this._meshPickProceed = false;
  25266. _this._updatePointerPosition(evt);
  25267. if (_this.preventDefaultOnPointerDown && canvas) {
  25268. evt.preventDefault();
  25269. canvas.focus();
  25270. }
  25271. // PreObservable support
  25272. if (_this.onPrePointerObservable.hasObservers()) {
  25273. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25274. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25275. _this.onPrePointerObservable.notifyObservers(pi, type);
  25276. if (pi.skipOnPointerObservable) {
  25277. return;
  25278. }
  25279. }
  25280. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25281. return;
  25282. }
  25283. _this._pointerCaptures[evt.pointerId] = true;
  25284. _this._startingPointerPosition.x = _this._pointerX;
  25285. _this._startingPointerPosition.y = _this._pointerY;
  25286. _this._startingPointerTime = Date.now();
  25287. if (!_this.pointerDownPredicate) {
  25288. _this.pointerDownPredicate = function (mesh) {
  25289. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25290. };
  25291. }
  25292. // Meshes
  25293. _this._pickedDownMesh = null;
  25294. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25295. _this._processPointerDown(pickResult, evt);
  25296. // Sprites
  25297. _this._pickedDownSprite = null;
  25298. if (_this.spriteManagers.length > 0) {
  25299. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25300. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25301. if (pickResult.pickedSprite.actionManager) {
  25302. _this._pickedDownSprite = pickResult.pickedSprite;
  25303. switch (evt.button) {
  25304. case 0:
  25305. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25306. break;
  25307. case 1:
  25308. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25309. break;
  25310. case 2:
  25311. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25312. break;
  25313. }
  25314. if (pickResult.pickedSprite.actionManager) {
  25315. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25316. }
  25317. }
  25318. }
  25319. }
  25320. };
  25321. this._onPointerUp = function (evt) {
  25322. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25323. return; // So we need to test it the pointer down was pressed before.
  25324. }
  25325. _this._totalPointersPressed--;
  25326. _this._pickedUpMesh = null;
  25327. _this._meshPickProceed = false;
  25328. _this._updatePointerPosition(evt);
  25329. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25330. // PreObservable support
  25331. if (_this.onPrePointerObservable.hasObservers()) {
  25332. if (!clickInfo.ignore) {
  25333. if (!clickInfo.hasSwiped) {
  25334. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25335. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25336. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25337. _this.onPrePointerObservable.notifyObservers(pi, type);
  25338. if (pi.skipOnPointerObservable) {
  25339. return;
  25340. }
  25341. }
  25342. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25343. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25344. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25345. _this.onPrePointerObservable.notifyObservers(pi, type);
  25346. if (pi.skipOnPointerObservable) {
  25347. return;
  25348. }
  25349. }
  25350. }
  25351. }
  25352. else {
  25353. var type = BABYLON.PointerEventTypes.POINTERUP;
  25354. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25355. _this.onPrePointerObservable.notifyObservers(pi, type);
  25356. if (pi.skipOnPointerObservable) {
  25357. return;
  25358. }
  25359. }
  25360. }
  25361. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25362. return;
  25363. }
  25364. _this._pointerCaptures[evt.pointerId] = false;
  25365. if (!_this.pointerUpPredicate) {
  25366. _this.pointerUpPredicate = function (mesh) {
  25367. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25368. };
  25369. }
  25370. // Meshes
  25371. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25372. _this._initActionManager(null, clickInfo);
  25373. }
  25374. if (!pickResult) {
  25375. pickResult = _this._currentPickResult;
  25376. }
  25377. _this._processPointerUp(pickResult, evt, clickInfo);
  25378. // Sprites
  25379. if (!clickInfo.ignore) {
  25380. if (_this.spriteManagers.length > 0) {
  25381. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25382. if (spritePickResult) {
  25383. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25384. if (spritePickResult.pickedSprite.actionManager) {
  25385. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25386. if (spritePickResult.pickedSprite.actionManager) {
  25387. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25388. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25389. }
  25390. }
  25391. }
  25392. }
  25393. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25394. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25395. }
  25396. }
  25397. }
  25398. }
  25399. _this._previousPickResult = _this._currentPickResult;
  25400. });
  25401. };
  25402. this._onKeyDown = function (evt) {
  25403. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25404. if (_this.onPreKeyboardObservable.hasObservers()) {
  25405. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25406. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25407. if (pi.skipOnPointerObservable) {
  25408. return;
  25409. }
  25410. }
  25411. if (_this.onKeyboardObservable.hasObservers()) {
  25412. var pi = new BABYLON.KeyboardInfo(type, evt);
  25413. _this.onKeyboardObservable.notifyObservers(pi, type);
  25414. }
  25415. if (_this.actionManager) {
  25416. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25417. }
  25418. };
  25419. this._onKeyUp = function (evt) {
  25420. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25421. if (_this.onPreKeyboardObservable.hasObservers()) {
  25422. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25423. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25424. if (pi.skipOnPointerObservable) {
  25425. return;
  25426. }
  25427. }
  25428. if (_this.onKeyboardObservable.hasObservers()) {
  25429. var pi = new BABYLON.KeyboardInfo(type, evt);
  25430. _this.onKeyboardObservable.notifyObservers(pi, type);
  25431. }
  25432. if (_this.actionManager) {
  25433. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25434. }
  25435. };
  25436. var engine = this.getEngine();
  25437. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25438. if (!canvas) {
  25439. return;
  25440. }
  25441. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25442. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25443. });
  25444. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25445. if (!canvas) {
  25446. return;
  25447. }
  25448. canvas.removeEventListener("keydown", _this._onKeyDown);
  25449. canvas.removeEventListener("keyup", _this._onKeyUp);
  25450. });
  25451. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25452. var canvas = this._engine.getRenderingCanvas();
  25453. if (!canvas) {
  25454. return;
  25455. }
  25456. if (attachMove) {
  25457. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25458. // Wheel
  25459. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25460. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25461. }
  25462. if (attachDown) {
  25463. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25464. }
  25465. if (attachUp) {
  25466. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25467. }
  25468. canvas.tabIndex = 1;
  25469. };
  25470. /** Detaches all event handlers*/
  25471. Scene.prototype.detachControl = function () {
  25472. var engine = this.getEngine();
  25473. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25474. var canvas = engine.getRenderingCanvas();
  25475. if (!canvas) {
  25476. return;
  25477. }
  25478. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25479. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25480. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25481. if (this._onCanvasBlurObserver) {
  25482. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25483. }
  25484. if (this._onCanvasFocusObserver) {
  25485. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25486. }
  25487. // Wheel
  25488. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25489. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25490. // Keyboard
  25491. canvas.removeEventListener("keydown", this._onKeyDown);
  25492. canvas.removeEventListener("keyup", this._onKeyUp);
  25493. // Observables
  25494. this.onKeyboardObservable.clear();
  25495. this.onPreKeyboardObservable.clear();
  25496. this.onPointerObservable.clear();
  25497. this.onPrePointerObservable.clear();
  25498. };
  25499. /**
  25500. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25501. * Delay loaded resources are not taking in account
  25502. * @return true if all required resources are ready
  25503. */
  25504. Scene.prototype.isReady = function () {
  25505. if (this._isDisposed) {
  25506. return false;
  25507. }
  25508. if (this._pendingData.length > 0) {
  25509. return false;
  25510. }
  25511. var index;
  25512. var engine = this.getEngine();
  25513. // Geometries
  25514. for (index = 0; index < this._geometries.length; index++) {
  25515. var geometry = this._geometries[index];
  25516. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25517. return false;
  25518. }
  25519. }
  25520. // Meshes
  25521. for (index = 0; index < this.meshes.length; index++) {
  25522. var mesh = this.meshes[index];
  25523. if (!mesh.isEnabled()) {
  25524. continue;
  25525. }
  25526. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25527. continue;
  25528. }
  25529. if (!mesh.isReady(true)) {
  25530. return false;
  25531. }
  25532. // Effect layers
  25533. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25534. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25535. var layer = _a[_i];
  25536. if (!layer.hasMesh(mesh)) {
  25537. continue;
  25538. }
  25539. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25540. var subMesh = _c[_b];
  25541. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25542. return false;
  25543. }
  25544. }
  25545. }
  25546. }
  25547. // Post-processes
  25548. if (this.activeCameras && this.activeCameras.length > 0) {
  25549. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25550. var camera = _e[_d];
  25551. if (!camera.isReady(true)) {
  25552. return false;
  25553. }
  25554. }
  25555. }
  25556. else if (this.activeCamera) {
  25557. if (!this.activeCamera.isReady(true)) {
  25558. return false;
  25559. }
  25560. }
  25561. // Particles
  25562. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25563. var particleSystem = _g[_f];
  25564. if (!particleSystem.isReady()) {
  25565. return false;
  25566. }
  25567. }
  25568. return true;
  25569. };
  25570. /** Resets all cached information relative to material (including effect and visibility) */
  25571. Scene.prototype.resetCachedMaterial = function () {
  25572. this._cachedMaterial = null;
  25573. this._cachedEffect = null;
  25574. this._cachedVisibility = null;
  25575. };
  25576. /**
  25577. * Registers a function to be called before every frame render
  25578. * @param func defines the function to register
  25579. */
  25580. Scene.prototype.registerBeforeRender = function (func) {
  25581. this.onBeforeRenderObservable.add(func);
  25582. };
  25583. /**
  25584. * Unregisters a function called before every frame render
  25585. * @param func defines the function to unregister
  25586. */
  25587. Scene.prototype.unregisterBeforeRender = function (func) {
  25588. this.onBeforeRenderObservable.removeCallback(func);
  25589. };
  25590. /**
  25591. * Registers a function to be called after every frame render
  25592. * @param func defines the function to register
  25593. */
  25594. Scene.prototype.registerAfterRender = function (func) {
  25595. this.onAfterRenderObservable.add(func);
  25596. };
  25597. /**
  25598. * Unregisters a function called after every frame render
  25599. * @param func defines the function to unregister
  25600. */
  25601. Scene.prototype.unregisterAfterRender = function (func) {
  25602. this.onAfterRenderObservable.removeCallback(func);
  25603. };
  25604. Scene.prototype._executeOnceBeforeRender = function (func) {
  25605. var _this = this;
  25606. var execFunc = function () {
  25607. func();
  25608. setTimeout(function () {
  25609. _this.unregisterBeforeRender(execFunc);
  25610. });
  25611. };
  25612. this.registerBeforeRender(execFunc);
  25613. };
  25614. /**
  25615. * The provided function will run before render once and will be disposed afterwards.
  25616. * A timeout delay can be provided so that the function will be executed in N ms.
  25617. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25618. * @param func The function to be executed.
  25619. * @param timeout optional delay in ms
  25620. */
  25621. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25622. var _this = this;
  25623. if (timeout !== undefined) {
  25624. setTimeout(function () {
  25625. _this._executeOnceBeforeRender(func);
  25626. }, timeout);
  25627. }
  25628. else {
  25629. this._executeOnceBeforeRender(func);
  25630. }
  25631. };
  25632. /** @hidden */
  25633. Scene.prototype._addPendingData = function (data) {
  25634. this._pendingData.push(data);
  25635. };
  25636. /** @hidden */
  25637. Scene.prototype._removePendingData = function (data) {
  25638. var wasLoading = this.isLoading;
  25639. var index = this._pendingData.indexOf(data);
  25640. if (index !== -1) {
  25641. this._pendingData.splice(index, 1);
  25642. }
  25643. if (wasLoading && !this.isLoading) {
  25644. this.onDataLoadedObservable.notifyObservers(this);
  25645. }
  25646. };
  25647. /**
  25648. * Returns the number of items waiting to be loaded
  25649. * @returns the number of items waiting to be loaded
  25650. */
  25651. Scene.prototype.getWaitingItemsCount = function () {
  25652. return this._pendingData.length;
  25653. };
  25654. Object.defineProperty(Scene.prototype, "isLoading", {
  25655. /**
  25656. * Returns a boolean indicating if the scene is still loading data
  25657. */
  25658. get: function () {
  25659. return this._pendingData.length > 0;
  25660. },
  25661. enumerable: true,
  25662. configurable: true
  25663. });
  25664. /**
  25665. * Registers a function to be executed when the scene is ready
  25666. * @param {Function} func - the function to be executed
  25667. */
  25668. Scene.prototype.executeWhenReady = function (func) {
  25669. var _this = this;
  25670. this.onReadyObservable.add(func);
  25671. if (this._executeWhenReadyTimeoutId !== -1) {
  25672. return;
  25673. }
  25674. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25675. _this._checkIsReady();
  25676. }, 150);
  25677. };
  25678. /**
  25679. * Returns a promise that resolves when the scene is ready
  25680. * @returns A promise that resolves when the scene is ready
  25681. */
  25682. Scene.prototype.whenReadyAsync = function () {
  25683. var _this = this;
  25684. return new Promise(function (resolve) {
  25685. _this.executeWhenReady(function () {
  25686. resolve();
  25687. });
  25688. });
  25689. };
  25690. /** @hidden */
  25691. Scene.prototype._checkIsReady = function () {
  25692. var _this = this;
  25693. if (this.isReady()) {
  25694. this.onReadyObservable.notifyObservers(this);
  25695. this.onReadyObservable.clear();
  25696. this._executeWhenReadyTimeoutId = -1;
  25697. return;
  25698. }
  25699. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25700. _this._checkIsReady();
  25701. }, 150);
  25702. };
  25703. // Animations
  25704. /**
  25705. * Will start the animation sequence of a given target
  25706. * @param target defines the target
  25707. * @param from defines from which frame should animation start
  25708. * @param to defines until which frame should animation run.
  25709. * @param weight defines the weight to apply to the animation (1.0 by default)
  25710. * @param loop defines if the animation loops
  25711. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25712. * @param onAnimationEnd defines the function to be executed when the animation ends
  25713. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25714. * @returns the animatable object created for this animation
  25715. */
  25716. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25717. if (weight === void 0) { weight = 1.0; }
  25718. if (speedRatio === void 0) { speedRatio = 1.0; }
  25719. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25720. returnedAnimatable.weight = weight;
  25721. return returnedAnimatable;
  25722. };
  25723. /**
  25724. * Will start the animation sequence of a given target
  25725. * @param target defines the target
  25726. * @param from defines from which frame should animation start
  25727. * @param to defines until which frame should animation run.
  25728. * @param loop defines if the animation loops
  25729. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25730. * @param onAnimationEnd defines the function to be executed when the animation ends
  25731. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25732. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25733. * @returns the animatable object created for this animation
  25734. */
  25735. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25736. if (speedRatio === void 0) { speedRatio = 1.0; }
  25737. if (stopCurrent === void 0) { stopCurrent = true; }
  25738. if (from > to && speedRatio > 0) {
  25739. speedRatio *= -1;
  25740. }
  25741. if (stopCurrent) {
  25742. this.stopAnimation(target);
  25743. }
  25744. if (!animatable) {
  25745. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25746. }
  25747. // Local animations
  25748. if (target.animations) {
  25749. animatable.appendAnimations(target, target.animations);
  25750. }
  25751. // Children animations
  25752. if (target.getAnimatables) {
  25753. var animatables = target.getAnimatables();
  25754. for (var index = 0; index < animatables.length; index++) {
  25755. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25756. }
  25757. }
  25758. animatable.reset();
  25759. return animatable;
  25760. };
  25761. /**
  25762. * Begin a new animation on a given node
  25763. * @param target defines the target where the animation will take place
  25764. * @param animations defines the list of animations to start
  25765. * @param from defines the initial value
  25766. * @param to defines the final value
  25767. * @param loop defines if you want animation to loop (off by default)
  25768. * @param speedRatio defines the speed ratio to apply to all animations
  25769. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25770. * @returns the list of created animatables
  25771. */
  25772. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25773. if (speedRatio === undefined) {
  25774. speedRatio = 1.0;
  25775. }
  25776. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25777. return animatable;
  25778. };
  25779. /**
  25780. * Begin a new animation on a given node and its hierarchy
  25781. * @param target defines the root node where the animation will take place
  25782. * @param 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.
  25783. * @param animations defines the list of animations to start
  25784. * @param from defines the initial value
  25785. * @param to defines the final value
  25786. * @param loop defines if you want animation to loop (off by default)
  25787. * @param speedRatio defines the speed ratio to apply to all animations
  25788. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25789. * @returns the list of animatables created for all nodes
  25790. */
  25791. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25792. var children = target.getDescendants(directDescendantsOnly);
  25793. var result = [];
  25794. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25795. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25796. var child = children_1[_i];
  25797. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25798. }
  25799. return result;
  25800. };
  25801. /**
  25802. * Gets the animatable associated with a specific target
  25803. * @param target defines the target of the animatable
  25804. * @returns the required animatable if found
  25805. */
  25806. Scene.prototype.getAnimatableByTarget = function (target) {
  25807. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25808. if (this._activeAnimatables[index].target === target) {
  25809. return this._activeAnimatables[index];
  25810. }
  25811. }
  25812. return null;
  25813. };
  25814. /**
  25815. * Gets all animatables associated with a given target
  25816. * @param target defines the target to look animatables for
  25817. * @returns an array of Animatables
  25818. */
  25819. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25820. var result = [];
  25821. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25822. if (this._activeAnimatables[index].target === target) {
  25823. result.push(this._activeAnimatables[index]);
  25824. }
  25825. }
  25826. return result;
  25827. };
  25828. Object.defineProperty(Scene.prototype, "animatables", {
  25829. /**
  25830. * Gets all animatable attached to the scene
  25831. */
  25832. get: function () {
  25833. return this._activeAnimatables;
  25834. },
  25835. enumerable: true,
  25836. configurable: true
  25837. });
  25838. /**
  25839. * Will stop the animation of the given target
  25840. * @param target - the target
  25841. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25842. */
  25843. Scene.prototype.stopAnimation = function (target, animationName) {
  25844. var animatables = this.getAllAnimatablesByTarget(target);
  25845. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25846. var animatable = animatables_1[_i];
  25847. animatable.stop(animationName);
  25848. }
  25849. };
  25850. /**
  25851. * Stops and removes all animations that have been applied to the scene
  25852. */
  25853. Scene.prototype.stopAllAnimations = function () {
  25854. if (this._activeAnimatables) {
  25855. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25856. this._activeAnimatables[i].stop();
  25857. }
  25858. this._activeAnimatables = [];
  25859. }
  25860. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25861. var group = _a[_i];
  25862. group.stop();
  25863. }
  25864. };
  25865. Scene.prototype._animate = function () {
  25866. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25867. return;
  25868. }
  25869. // Getting time
  25870. var now = BABYLON.Tools.Now;
  25871. if (!this._animationTimeLast) {
  25872. if (this._pendingData.length > 0) {
  25873. return;
  25874. }
  25875. this._animationTimeLast = now;
  25876. }
  25877. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25878. this._animationTime += deltaTime;
  25879. this._animationTimeLast = now;
  25880. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25881. this._activeAnimatables[index]._animate(this._animationTime);
  25882. }
  25883. // Late animation bindings
  25884. this._processLateAnimationBindings();
  25885. };
  25886. /** @hidden */
  25887. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25888. var target = runtimeAnimation.target;
  25889. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25890. if (!target._lateAnimationHolders) {
  25891. target._lateAnimationHolders = {};
  25892. }
  25893. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25894. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25895. totalWeight: 0,
  25896. animations: [],
  25897. originalValue: originalValue
  25898. };
  25899. }
  25900. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25901. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25902. };
  25903. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25904. var normalizer = 1.0;
  25905. var finalPosition = BABYLON.Tmp.Vector3[0];
  25906. var finalScaling = BABYLON.Tmp.Vector3[1];
  25907. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25908. var startIndex = 0;
  25909. var originalAnimation = holder.animations[0];
  25910. var originalValue = holder.originalValue;
  25911. var scale = 1;
  25912. if (holder.totalWeight < 1.0) {
  25913. // We need to mix the original value in
  25914. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25915. scale = 1.0 - holder.totalWeight;
  25916. }
  25917. else {
  25918. startIndex = 1;
  25919. // We need to normalize the weights
  25920. normalizer = holder.totalWeight;
  25921. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25922. scale = originalAnimation.weight / normalizer;
  25923. if (scale == 1) {
  25924. return originalAnimation.currentValue;
  25925. }
  25926. }
  25927. finalScaling.scaleInPlace(scale);
  25928. finalPosition.scaleInPlace(scale);
  25929. finalQuaternion.scaleInPlace(scale);
  25930. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25931. var runtimeAnimation = holder.animations[animIndex];
  25932. var scale = runtimeAnimation.weight / normalizer;
  25933. var currentPosition = BABYLON.Tmp.Vector3[2];
  25934. var currentScaling = BABYLON.Tmp.Vector3[3];
  25935. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25936. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25937. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25938. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25939. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25940. }
  25941. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25942. return originalAnimation._workValue;
  25943. };
  25944. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25945. var originalAnimation = holder.animations[0];
  25946. var originalValue = holder.originalValue;
  25947. if (holder.animations.length === 1) {
  25948. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25949. }
  25950. var normalizer = 1.0;
  25951. var quaternions;
  25952. var weights;
  25953. if (holder.totalWeight < 1.0) {
  25954. var scale = 1.0 - holder.totalWeight;
  25955. quaternions = [];
  25956. weights = [];
  25957. quaternions.push(originalValue);
  25958. weights.push(scale);
  25959. }
  25960. else {
  25961. if (holder.animations.length === 2) { // Slerp as soon as we can
  25962. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25963. }
  25964. quaternions = [];
  25965. weights = [];
  25966. normalizer = holder.totalWeight;
  25967. }
  25968. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25969. var runtimeAnimation = holder.animations[animIndex];
  25970. quaternions.push(runtimeAnimation.currentValue);
  25971. weights.push(runtimeAnimation.weight / normalizer);
  25972. }
  25973. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25974. var cumulativeAmount = 0;
  25975. var cumulativeQuaternion = null;
  25976. for (var index = 0; index < quaternions.length;) {
  25977. if (!cumulativeQuaternion) {
  25978. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25979. cumulativeAmount = weights[index] + weights[index + 1];
  25980. index += 2;
  25981. continue;
  25982. }
  25983. cumulativeAmount += weights[index];
  25984. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25985. index++;
  25986. }
  25987. return cumulativeQuaternion;
  25988. };
  25989. Scene.prototype._processLateAnimationBindings = function () {
  25990. if (!this._registeredForLateAnimationBindings.length) {
  25991. return;
  25992. }
  25993. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25994. var target = this._registeredForLateAnimationBindings.data[index];
  25995. for (var path in target._lateAnimationHolders) {
  25996. var holder = target._lateAnimationHolders[path];
  25997. var originalAnimation = holder.animations[0];
  25998. var originalValue = holder.originalValue;
  25999. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26000. var finalValue = void 0;
  26001. if (matrixDecomposeMode) {
  26002. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26003. }
  26004. else {
  26005. var quaternionMode = originalValue.w !== undefined;
  26006. if (quaternionMode) {
  26007. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26008. }
  26009. else {
  26010. var startIndex = 0;
  26011. var normalizer = 1.0;
  26012. if (holder.totalWeight < 1.0) {
  26013. // We need to mix the original value in
  26014. if (originalValue.scale) {
  26015. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26016. }
  26017. else {
  26018. finalValue = originalValue * (1.0 - holder.totalWeight);
  26019. }
  26020. }
  26021. else {
  26022. // We need to normalize the weights
  26023. normalizer = holder.totalWeight;
  26024. var scale_1 = originalAnimation.weight / normalizer;
  26025. if (scale_1 !== 1) {
  26026. if (originalAnimation.currentValue.scale) {
  26027. finalValue = originalAnimation.currentValue.scale(scale_1);
  26028. }
  26029. else {
  26030. finalValue = originalAnimation.currentValue * scale_1;
  26031. }
  26032. }
  26033. else {
  26034. finalValue = originalAnimation.currentValue;
  26035. }
  26036. startIndex = 1;
  26037. }
  26038. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26039. var runtimeAnimation = holder.animations[animIndex];
  26040. var scale = runtimeAnimation.weight / normalizer;
  26041. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26042. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26043. }
  26044. else {
  26045. finalValue += runtimeAnimation.currentValue * scale;
  26046. }
  26047. }
  26048. }
  26049. }
  26050. target[path] = finalValue;
  26051. }
  26052. target._lateAnimationHolders = {};
  26053. }
  26054. this._registeredForLateAnimationBindings.reset();
  26055. };
  26056. // Matrix
  26057. /** @hidden */
  26058. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26059. this._useAlternateCameraConfiguration = active;
  26060. };
  26061. /**
  26062. * Gets the current view matrix
  26063. * @returns a Matrix
  26064. */
  26065. Scene.prototype.getViewMatrix = function () {
  26066. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26067. };
  26068. /**
  26069. * Gets the current projection matrix
  26070. * @returns a Matrix
  26071. */
  26072. Scene.prototype.getProjectionMatrix = function () {
  26073. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26074. };
  26075. /**
  26076. * Gets the current transform matrix
  26077. * @returns a Matrix made of View * Projection
  26078. */
  26079. Scene.prototype.getTransformMatrix = function () {
  26080. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26081. };
  26082. /**
  26083. * Sets the current transform matrix
  26084. * @param view defines the View matrix to use
  26085. * @param projection defines the Projection matrix to use
  26086. */
  26087. Scene.prototype.setTransformMatrix = function (view, projection) {
  26088. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26089. return;
  26090. }
  26091. this._viewUpdateFlag = view.updateFlag;
  26092. this._projectionUpdateFlag = projection.updateFlag;
  26093. this._viewMatrix = view;
  26094. this._projectionMatrix = projection;
  26095. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26096. // Update frustum
  26097. if (!this._frustumPlanes) {
  26098. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26099. }
  26100. else {
  26101. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26102. }
  26103. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26104. var otherCamera = this.activeCamera._alternateCamera;
  26105. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26106. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26107. }
  26108. if (this._sceneUbo.useUbo) {
  26109. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26110. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26111. this._sceneUbo.update();
  26112. }
  26113. };
  26114. /** @hidden */
  26115. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26116. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26117. return;
  26118. }
  26119. this._alternateViewUpdateFlag = view.updateFlag;
  26120. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26121. this._alternateViewMatrix = view;
  26122. this._alternateProjectionMatrix = projection;
  26123. if (!this._alternateTransformMatrix) {
  26124. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26125. }
  26126. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26127. if (!this._alternateSceneUbo) {
  26128. this._createAlternateUbo();
  26129. }
  26130. if (this._alternateSceneUbo.useUbo) {
  26131. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26132. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26133. this._alternateSceneUbo.update();
  26134. }
  26135. };
  26136. /**
  26137. * Gets the uniform buffer used to store scene data
  26138. * @returns a UniformBuffer
  26139. */
  26140. Scene.prototype.getSceneUniformBuffer = function () {
  26141. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26142. };
  26143. /**
  26144. * Gets an unique (relatively to the current scene) Id
  26145. * @returns an unique number for the scene
  26146. */
  26147. Scene.prototype.getUniqueId = function () {
  26148. var result = Scene._uniqueIdCounter;
  26149. Scene._uniqueIdCounter++;
  26150. return result;
  26151. };
  26152. /**
  26153. * Add a mesh to the list of scene's meshes
  26154. * @param newMesh defines the mesh to add
  26155. */
  26156. Scene.prototype.addMesh = function (newMesh) {
  26157. this.meshes.push(newMesh);
  26158. //notify the collision coordinator
  26159. if (this.collisionCoordinator) {
  26160. this.collisionCoordinator.onMeshAdded(newMesh);
  26161. }
  26162. newMesh._resyncLightSources();
  26163. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26164. };
  26165. /**
  26166. * Remove a mesh for the list of scene's meshes
  26167. * @param toRemove defines the mesh to remove
  26168. * @param recursive if all child meshes should also be removed from the scene
  26169. * @returns the index where the mesh was in the mesh list
  26170. */
  26171. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26172. var _this = this;
  26173. if (recursive === void 0) { recursive = false; }
  26174. var index = this.meshes.indexOf(toRemove);
  26175. if (index !== -1) {
  26176. // Remove from the scene if mesh found
  26177. this.meshes.splice(index, 1);
  26178. }
  26179. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26180. if (recursive) {
  26181. toRemove.getChildMeshes().forEach(function (m) {
  26182. _this.removeMesh(m);
  26183. });
  26184. }
  26185. return index;
  26186. };
  26187. /**
  26188. * Add a transform node to the list of scene's transform nodes
  26189. * @param newTransformNode defines the transform node to add
  26190. */
  26191. Scene.prototype.addTransformNode = function (newTransformNode) {
  26192. this.transformNodes.push(newTransformNode);
  26193. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26194. };
  26195. /**
  26196. * Remove a transform node for the list of scene's transform nodes
  26197. * @param toRemove defines the transform node to remove
  26198. * @returns the index where the transform node was in the transform node list
  26199. */
  26200. Scene.prototype.removeTransformNode = function (toRemove) {
  26201. var index = this.transformNodes.indexOf(toRemove);
  26202. if (index !== -1) {
  26203. // Remove from the scene if found
  26204. this.transformNodes.splice(index, 1);
  26205. }
  26206. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26207. return index;
  26208. };
  26209. /**
  26210. * Remove a skeleton for the list of scene's skeletons
  26211. * @param toRemove defines the skeleton to remove
  26212. * @returns the index where the skeleton was in the skeleton list
  26213. */
  26214. Scene.prototype.removeSkeleton = function (toRemove) {
  26215. var index = this.skeletons.indexOf(toRemove);
  26216. if (index !== -1) {
  26217. // Remove from the scene if found
  26218. this.skeletons.splice(index, 1);
  26219. }
  26220. return index;
  26221. };
  26222. /**
  26223. * Remove a morph target for the list of scene's morph targets
  26224. * @param toRemove defines the morph target to remove
  26225. * @returns the index where the morph target was in the morph target list
  26226. */
  26227. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26228. var index = this.morphTargetManagers.indexOf(toRemove);
  26229. if (index !== -1) {
  26230. // Remove from the scene if found
  26231. this.morphTargetManagers.splice(index, 1);
  26232. }
  26233. return index;
  26234. };
  26235. /**
  26236. * Remove a light for the list of scene's lights
  26237. * @param toRemove defines the light to remove
  26238. * @returns the index where the light was in the light list
  26239. */
  26240. Scene.prototype.removeLight = function (toRemove) {
  26241. var index = this.lights.indexOf(toRemove);
  26242. if (index !== -1) {
  26243. // Remove from meshes
  26244. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26245. var mesh = _a[_i];
  26246. mesh._removeLightSource(toRemove);
  26247. }
  26248. // Remove from the scene if mesh found
  26249. this.lights.splice(index, 1);
  26250. this.sortLightsByPriority();
  26251. }
  26252. this.onLightRemovedObservable.notifyObservers(toRemove);
  26253. return index;
  26254. };
  26255. /**
  26256. * Remove a camera for the list of scene's cameras
  26257. * @param toRemove defines the camera to remove
  26258. * @returns the index where the camera was in the camera list
  26259. */
  26260. Scene.prototype.removeCamera = function (toRemove) {
  26261. var index = this.cameras.indexOf(toRemove);
  26262. if (index !== -1) {
  26263. // Remove from the scene if mesh found
  26264. this.cameras.splice(index, 1);
  26265. }
  26266. // Remove from activeCameras
  26267. var index2 = this.activeCameras.indexOf(toRemove);
  26268. if (index2 !== -1) {
  26269. // Remove from the scene if mesh found
  26270. this.activeCameras.splice(index2, 1);
  26271. }
  26272. // Reset the activeCamera
  26273. if (this.activeCamera === toRemove) {
  26274. if (this.cameras.length > 0) {
  26275. this.activeCamera = this.cameras[0];
  26276. }
  26277. else {
  26278. this.activeCamera = null;
  26279. }
  26280. }
  26281. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26282. return index;
  26283. };
  26284. /**
  26285. * Remove a particle system for the list of scene's particle systems
  26286. * @param toRemove defines the particle system to remove
  26287. * @returns the index where the particle system was in the particle system list
  26288. */
  26289. Scene.prototype.removeParticleSystem = function (toRemove) {
  26290. var index = this.particleSystems.indexOf(toRemove);
  26291. if (index !== -1) {
  26292. this.particleSystems.splice(index, 1);
  26293. }
  26294. return index;
  26295. };
  26296. /**
  26297. * Remove a animation for the list of scene's animations
  26298. * @param toRemove defines the animation to remove
  26299. * @returns the index where the animation was in the animation list
  26300. */
  26301. Scene.prototype.removeAnimation = function (toRemove) {
  26302. var index = this.animations.indexOf(toRemove);
  26303. if (index !== -1) {
  26304. this.animations.splice(index, 1);
  26305. }
  26306. return index;
  26307. };
  26308. /**
  26309. * Removes the given animation group from this scene.
  26310. * @param toRemove The animation group to remove
  26311. * @returns The index of the removed animation group
  26312. */
  26313. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26314. var index = this.animationGroups.indexOf(toRemove);
  26315. if (index !== -1) {
  26316. this.animationGroups.splice(index, 1);
  26317. }
  26318. return index;
  26319. };
  26320. /**
  26321. * Removes the given multi-material from this scene.
  26322. * @param toRemove The multi-material to remove
  26323. * @returns The index of the removed multi-material
  26324. */
  26325. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26326. var index = this.multiMaterials.indexOf(toRemove);
  26327. if (index !== -1) {
  26328. this.multiMaterials.splice(index, 1);
  26329. }
  26330. return index;
  26331. };
  26332. /**
  26333. * Removes the given material from this scene.
  26334. * @param toRemove The material to remove
  26335. * @returns The index of the removed material
  26336. */
  26337. Scene.prototype.removeMaterial = function (toRemove) {
  26338. var index = this.materials.indexOf(toRemove);
  26339. if (index !== -1) {
  26340. this.materials.splice(index, 1);
  26341. }
  26342. return index;
  26343. };
  26344. /**
  26345. * Removes the given lens flare system from this scene.
  26346. * @param toRemove The lens flare system to remove
  26347. * @returns The index of the removed lens flare system
  26348. */
  26349. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26350. var index = this.lensFlareSystems.indexOf(toRemove);
  26351. if (index !== -1) {
  26352. this.lensFlareSystems.splice(index, 1);
  26353. }
  26354. return index;
  26355. };
  26356. /**
  26357. * Removes the given action manager from this scene.
  26358. * @param toRemove The action manager to remove
  26359. * @returns The index of the removed action manager
  26360. */
  26361. Scene.prototype.removeActionManager = function (toRemove) {
  26362. var index = this._actionManagers.indexOf(toRemove);
  26363. if (index !== -1) {
  26364. this._actionManagers.splice(index, 1);
  26365. }
  26366. return index;
  26367. };
  26368. /**
  26369. * Removes the given effect layer from this scene.
  26370. * @param toRemove defines the effect layer to remove
  26371. * @returns the index of the removed effect layer
  26372. */
  26373. Scene.prototype.removeEffectLayer = function (toRemove) {
  26374. var index = this.effectLayers.indexOf(toRemove);
  26375. if (index !== -1) {
  26376. this.effectLayers.splice(index, 1);
  26377. }
  26378. return index;
  26379. };
  26380. /**
  26381. * Removes the given texture from this scene.
  26382. * @param toRemove The texture to remove
  26383. * @returns The index of the removed texture
  26384. */
  26385. Scene.prototype.removeTexture = function (toRemove) {
  26386. var index = this.textures.indexOf(toRemove);
  26387. if (index !== -1) {
  26388. this.textures.splice(index, 1);
  26389. }
  26390. return index;
  26391. };
  26392. /**
  26393. * Adds the given light to this scene
  26394. * @param newLight The light to add
  26395. */
  26396. Scene.prototype.addLight = function (newLight) {
  26397. this.lights.push(newLight);
  26398. this.sortLightsByPriority();
  26399. // Add light to all meshes (To support if the light is removed and then readded)
  26400. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26401. var mesh = _a[_i];
  26402. if (mesh._lightSources.indexOf(newLight) === -1) {
  26403. mesh._lightSources.push(newLight);
  26404. mesh._resyncLightSources();
  26405. }
  26406. }
  26407. this.onNewLightAddedObservable.notifyObservers(newLight);
  26408. };
  26409. /**
  26410. * Sorts the list list based on light priorities
  26411. */
  26412. Scene.prototype.sortLightsByPriority = function () {
  26413. if (this.requireLightSorting) {
  26414. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26415. }
  26416. };
  26417. /**
  26418. * Adds the given camera to this scene
  26419. * @param newCamera The camera to add
  26420. */
  26421. Scene.prototype.addCamera = function (newCamera) {
  26422. this.cameras.push(newCamera);
  26423. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26424. };
  26425. /**
  26426. * Adds the given skeleton to this scene
  26427. * @param newSkeleton The skeleton to add
  26428. */
  26429. Scene.prototype.addSkeleton = function (newSkeleton) {
  26430. this.skeletons.push(newSkeleton);
  26431. };
  26432. /**
  26433. * Adds the given particle system to this scene
  26434. * @param newParticleSystem The particle system to add
  26435. */
  26436. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26437. this.particleSystems.push(newParticleSystem);
  26438. };
  26439. /**
  26440. * Adds the given animation to this scene
  26441. * @param newAnimation The animation to add
  26442. */
  26443. Scene.prototype.addAnimation = function (newAnimation) {
  26444. this.animations.push(newAnimation);
  26445. };
  26446. /**
  26447. * Adds the given animation group to this scene.
  26448. * @param newAnimationGroup The animation group to add
  26449. */
  26450. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26451. this.animationGroups.push(newAnimationGroup);
  26452. };
  26453. /**
  26454. * Adds the given multi-material to this scene
  26455. * @param newMultiMaterial The multi-material to add
  26456. */
  26457. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26458. this.multiMaterials.push(newMultiMaterial);
  26459. };
  26460. /**
  26461. * Adds the given material to this scene
  26462. * @param newMaterial The material to add
  26463. */
  26464. Scene.prototype.addMaterial = function (newMaterial) {
  26465. this.materials.push(newMaterial);
  26466. };
  26467. /**
  26468. * Adds the given morph target to this scene
  26469. * @param newMorphTargetManager The morph target to add
  26470. */
  26471. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26472. this.morphTargetManagers.push(newMorphTargetManager);
  26473. };
  26474. /**
  26475. * Adds the given geometry to this scene
  26476. * @param newGeometry The geometry to add
  26477. */
  26478. Scene.prototype.addGeometry = function (newGeometry) {
  26479. this._geometries.push(newGeometry);
  26480. };
  26481. /**
  26482. * Adds the given lens flare system to this scene
  26483. * @param newLensFlareSystem The lens flare system to add
  26484. */
  26485. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26486. this.lensFlareSystems.push(newLensFlareSystem);
  26487. };
  26488. /**
  26489. * Adds the given effect layer to this scene
  26490. * @param newEffectLayer defines the effect layer to add
  26491. */
  26492. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26493. this.effectLayers.push(newEffectLayer);
  26494. };
  26495. /**
  26496. * Adds the given action manager to this scene
  26497. * @param newActionManager The action manager to add
  26498. */
  26499. Scene.prototype.addActionManager = function (newActionManager) {
  26500. this._actionManagers.push(newActionManager);
  26501. };
  26502. /**
  26503. * Adds the given texture to this scene.
  26504. * @param newTexture The texture to add
  26505. */
  26506. Scene.prototype.addTexture = function (newTexture) {
  26507. this.textures.push(newTexture);
  26508. };
  26509. /**
  26510. * Switch active camera
  26511. * @param newCamera defines the new active camera
  26512. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26513. */
  26514. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26515. if (attachControl === void 0) { attachControl = true; }
  26516. var canvas = this._engine.getRenderingCanvas();
  26517. if (!canvas) {
  26518. return;
  26519. }
  26520. if (this.activeCamera) {
  26521. this.activeCamera.detachControl(canvas);
  26522. }
  26523. this.activeCamera = newCamera;
  26524. if (attachControl) {
  26525. newCamera.attachControl(canvas);
  26526. }
  26527. };
  26528. /**
  26529. * sets the active camera of the scene using its ID
  26530. * @param id defines the camera's ID
  26531. * @return the new active camera or null if none found.
  26532. */
  26533. Scene.prototype.setActiveCameraByID = function (id) {
  26534. var camera = this.getCameraByID(id);
  26535. if (camera) {
  26536. this.activeCamera = camera;
  26537. return camera;
  26538. }
  26539. return null;
  26540. };
  26541. /**
  26542. * sets the active camera of the scene using its name
  26543. * @param name defines the camera's name
  26544. * @returns the new active camera or null if none found.
  26545. */
  26546. Scene.prototype.setActiveCameraByName = function (name) {
  26547. var camera = this.getCameraByName(name);
  26548. if (camera) {
  26549. this.activeCamera = camera;
  26550. return camera;
  26551. }
  26552. return null;
  26553. };
  26554. /**
  26555. * get an animation group using its name
  26556. * @param name defines the material's name
  26557. * @return the animation group or null if none found.
  26558. */
  26559. Scene.prototype.getAnimationGroupByName = function (name) {
  26560. for (var index = 0; index < this.animationGroups.length; index++) {
  26561. if (this.animationGroups[index].name === name) {
  26562. return this.animationGroups[index];
  26563. }
  26564. }
  26565. return null;
  26566. };
  26567. /**
  26568. * get a material using its id
  26569. * @param id defines the material's ID
  26570. * @return the material or null if none found.
  26571. */
  26572. Scene.prototype.getMaterialByID = function (id) {
  26573. for (var index = 0; index < this.materials.length; index++) {
  26574. if (this.materials[index].id === id) {
  26575. return this.materials[index];
  26576. }
  26577. }
  26578. return null;
  26579. };
  26580. /**
  26581. * Gets a material using its name
  26582. * @param name defines the material's name
  26583. * @return the material or null if none found.
  26584. */
  26585. Scene.prototype.getMaterialByName = function (name) {
  26586. for (var index = 0; index < this.materials.length; index++) {
  26587. if (this.materials[index].name === name) {
  26588. return this.materials[index];
  26589. }
  26590. }
  26591. return null;
  26592. };
  26593. /**
  26594. * Gets a lens flare system using its name
  26595. * @param name defines the name to look for
  26596. * @returns the lens flare system or null if not found
  26597. */
  26598. Scene.prototype.getLensFlareSystemByName = function (name) {
  26599. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26600. if (this.lensFlareSystems[index].name === name) {
  26601. return this.lensFlareSystems[index];
  26602. }
  26603. }
  26604. return null;
  26605. };
  26606. /**
  26607. * Gets a lens flare system using its id
  26608. * @param id defines the id to look for
  26609. * @returns the lens flare system or null if not found
  26610. */
  26611. Scene.prototype.getLensFlareSystemByID = function (id) {
  26612. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26613. if (this.lensFlareSystems[index].id === id) {
  26614. return this.lensFlareSystems[index];
  26615. }
  26616. }
  26617. return null;
  26618. };
  26619. /**
  26620. * Gets a camera using its id
  26621. * @param id defines the id to look for
  26622. * @returns the camera or null if not found
  26623. */
  26624. Scene.prototype.getCameraByID = function (id) {
  26625. for (var index = 0; index < this.cameras.length; index++) {
  26626. if (this.cameras[index].id === id) {
  26627. return this.cameras[index];
  26628. }
  26629. }
  26630. return null;
  26631. };
  26632. /**
  26633. * Gets a camera using its unique id
  26634. * @param uniqueId defines the unique id to look for
  26635. * @returns the camera or null if not found
  26636. */
  26637. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26638. for (var index = 0; index < this.cameras.length; index++) {
  26639. if (this.cameras[index].uniqueId === uniqueId) {
  26640. return this.cameras[index];
  26641. }
  26642. }
  26643. return null;
  26644. };
  26645. /**
  26646. * Gets a camera using its name
  26647. * @param name defines the camera's name
  26648. * @return the camera or null if none found.
  26649. */
  26650. Scene.prototype.getCameraByName = function (name) {
  26651. for (var index = 0; index < this.cameras.length; index++) {
  26652. if (this.cameras[index].name === name) {
  26653. return this.cameras[index];
  26654. }
  26655. }
  26656. return null;
  26657. };
  26658. /**
  26659. * Gets a bone using its id
  26660. * @param id defines the bone's id
  26661. * @return the bone or null if not found
  26662. */
  26663. Scene.prototype.getBoneByID = function (id) {
  26664. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26665. var skeleton = this.skeletons[skeletonIndex];
  26666. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26667. if (skeleton.bones[boneIndex].id === id) {
  26668. return skeleton.bones[boneIndex];
  26669. }
  26670. }
  26671. }
  26672. return null;
  26673. };
  26674. /**
  26675. * Gets a bone using its id
  26676. * @param name defines the bone's name
  26677. * @return the bone or null if not found
  26678. */
  26679. Scene.prototype.getBoneByName = function (name) {
  26680. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26681. var skeleton = this.skeletons[skeletonIndex];
  26682. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26683. if (skeleton.bones[boneIndex].name === name) {
  26684. return skeleton.bones[boneIndex];
  26685. }
  26686. }
  26687. }
  26688. return null;
  26689. };
  26690. /**
  26691. * Gets a light node using its name
  26692. * @param name defines the the light's name
  26693. * @return the light or null if none found.
  26694. */
  26695. Scene.prototype.getLightByName = function (name) {
  26696. for (var index = 0; index < this.lights.length; index++) {
  26697. if (this.lights[index].name === name) {
  26698. return this.lights[index];
  26699. }
  26700. }
  26701. return null;
  26702. };
  26703. /**
  26704. * Gets a light node using its id
  26705. * @param id defines the light's id
  26706. * @return the light or null if none found.
  26707. */
  26708. Scene.prototype.getLightByID = function (id) {
  26709. for (var index = 0; index < this.lights.length; index++) {
  26710. if (this.lights[index].id === id) {
  26711. return this.lights[index];
  26712. }
  26713. }
  26714. return null;
  26715. };
  26716. /**
  26717. * Gets a light node using its scene-generated unique ID
  26718. * @param uniqueId defines the light's unique id
  26719. * @return the light or null if none found.
  26720. */
  26721. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26722. for (var index = 0; index < this.lights.length; index++) {
  26723. if (this.lights[index].uniqueId === uniqueId) {
  26724. return this.lights[index];
  26725. }
  26726. }
  26727. return null;
  26728. };
  26729. /**
  26730. * Gets a particle system by id
  26731. * @param id defines the particle system id
  26732. * @return the corresponding system or null if none found
  26733. */
  26734. Scene.prototype.getParticleSystemByID = function (id) {
  26735. for (var index = 0; index < this.particleSystems.length; index++) {
  26736. if (this.particleSystems[index].id === id) {
  26737. return this.particleSystems[index];
  26738. }
  26739. }
  26740. return null;
  26741. };
  26742. /**
  26743. * Gets a geometry using its ID
  26744. * @param id defines the geometry's id
  26745. * @return the geometry or null if none found.
  26746. */
  26747. Scene.prototype.getGeometryByID = function (id) {
  26748. for (var index = 0; index < this._geometries.length; index++) {
  26749. if (this._geometries[index].id === id) {
  26750. return this._geometries[index];
  26751. }
  26752. }
  26753. return null;
  26754. };
  26755. /**
  26756. * Add a new geometry to this scene
  26757. * @param geometry defines the geometry to be added to the scene.
  26758. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26759. * @return a boolean defining if the geometry was added or not
  26760. */
  26761. Scene.prototype.pushGeometry = function (geometry, force) {
  26762. if (!force && this.getGeometryByID(geometry.id)) {
  26763. return false;
  26764. }
  26765. this._geometries.push(geometry);
  26766. //notify the collision coordinator
  26767. if (this.collisionCoordinator) {
  26768. this.collisionCoordinator.onGeometryAdded(geometry);
  26769. }
  26770. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26771. return true;
  26772. };
  26773. /**
  26774. * Removes an existing geometry
  26775. * @param geometry defines the geometry to be removed from the scene
  26776. * @return a boolean defining if the geometry was removed or not
  26777. */
  26778. Scene.prototype.removeGeometry = function (geometry) {
  26779. var index = this._geometries.indexOf(geometry);
  26780. if (index > -1) {
  26781. this._geometries.splice(index, 1);
  26782. //notify the collision coordinator
  26783. if (this.collisionCoordinator) {
  26784. this.collisionCoordinator.onGeometryDeleted(geometry);
  26785. }
  26786. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26787. return true;
  26788. }
  26789. return false;
  26790. };
  26791. /**
  26792. * Gets the list of geometries attached to the scene
  26793. * @returns an array of Geometry
  26794. */
  26795. Scene.prototype.getGeometries = function () {
  26796. return this._geometries;
  26797. };
  26798. /**
  26799. * Gets the first added mesh found of a given ID
  26800. * @param id defines the id to search for
  26801. * @return the mesh found or null if not found at all
  26802. */
  26803. Scene.prototype.getMeshByID = function (id) {
  26804. for (var index = 0; index < this.meshes.length; index++) {
  26805. if (this.meshes[index].id === id) {
  26806. return this.meshes[index];
  26807. }
  26808. }
  26809. return null;
  26810. };
  26811. /**
  26812. * Gets a list of meshes using their id
  26813. * @param id defines the id to search for
  26814. * @returns a list of meshes
  26815. */
  26816. Scene.prototype.getMeshesByID = function (id) {
  26817. return this.meshes.filter(function (m) {
  26818. return m.id === id;
  26819. });
  26820. };
  26821. /**
  26822. * Gets the first added transform node found of a given ID
  26823. * @param id defines the id to search for
  26824. * @return the found transform node or null if not found at all.
  26825. */
  26826. Scene.prototype.getTransformNodeByID = function (id) {
  26827. for (var index = 0; index < this.transformNodes.length; index++) {
  26828. if (this.transformNodes[index].id === id) {
  26829. return this.transformNodes[index];
  26830. }
  26831. }
  26832. return null;
  26833. };
  26834. /**
  26835. * Gets a list of transform nodes using their id
  26836. * @param id defines the id to search for
  26837. * @returns a list of transform nodes
  26838. */
  26839. Scene.prototype.getTransformNodesByID = function (id) {
  26840. return this.transformNodes.filter(function (m) {
  26841. return m.id === id;
  26842. });
  26843. };
  26844. /**
  26845. * Gets a mesh with its auto-generated unique id
  26846. * @param uniqueId defines the unique id to search for
  26847. * @return the found mesh or null if not found at all.
  26848. */
  26849. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26850. for (var index = 0; index < this.meshes.length; index++) {
  26851. if (this.meshes[index].uniqueId === uniqueId) {
  26852. return this.meshes[index];
  26853. }
  26854. }
  26855. return null;
  26856. };
  26857. /**
  26858. * Gets a the last added mesh using a given id
  26859. * @param id defines the id to search for
  26860. * @return the found mesh or null if not found at all.
  26861. */
  26862. Scene.prototype.getLastMeshByID = function (id) {
  26863. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26864. if (this.meshes[index].id === id) {
  26865. return this.meshes[index];
  26866. }
  26867. }
  26868. return null;
  26869. };
  26870. /**
  26871. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26872. * @param id defines the id to search for
  26873. * @return the found node or null if not found at all
  26874. */
  26875. Scene.prototype.getLastEntryByID = function (id) {
  26876. var index;
  26877. for (index = this.meshes.length - 1; index >= 0; index--) {
  26878. if (this.meshes[index].id === id) {
  26879. return this.meshes[index];
  26880. }
  26881. }
  26882. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26883. if (this.transformNodes[index].id === id) {
  26884. return this.transformNodes[index];
  26885. }
  26886. }
  26887. for (index = this.cameras.length - 1; index >= 0; index--) {
  26888. if (this.cameras[index].id === id) {
  26889. return this.cameras[index];
  26890. }
  26891. }
  26892. for (index = this.lights.length - 1; index >= 0; index--) {
  26893. if (this.lights[index].id === id) {
  26894. return this.lights[index];
  26895. }
  26896. }
  26897. return null;
  26898. };
  26899. /**
  26900. * Gets a node (Mesh, Camera, Light) using a given id
  26901. * @param id defines the id to search for
  26902. * @return the found node or null if not found at all
  26903. */
  26904. Scene.prototype.getNodeByID = function (id) {
  26905. var mesh = this.getMeshByID(id);
  26906. if (mesh) {
  26907. return mesh;
  26908. }
  26909. var light = this.getLightByID(id);
  26910. if (light) {
  26911. return light;
  26912. }
  26913. var camera = this.getCameraByID(id);
  26914. if (camera) {
  26915. return camera;
  26916. }
  26917. var bone = this.getBoneByID(id);
  26918. return bone;
  26919. };
  26920. /**
  26921. * Gets a node (Mesh, Camera, Light) using a given name
  26922. * @param name defines the name to search for
  26923. * @return the found node or null if not found at all.
  26924. */
  26925. Scene.prototype.getNodeByName = function (name) {
  26926. var mesh = this.getMeshByName(name);
  26927. if (mesh) {
  26928. return mesh;
  26929. }
  26930. var light = this.getLightByName(name);
  26931. if (light) {
  26932. return light;
  26933. }
  26934. var camera = this.getCameraByName(name);
  26935. if (camera) {
  26936. return camera;
  26937. }
  26938. var bone = this.getBoneByName(name);
  26939. return bone;
  26940. };
  26941. /**
  26942. * Gets a mesh using a given name
  26943. * @param name defines the name to search for
  26944. * @return the found mesh or null if not found at all.
  26945. */
  26946. Scene.prototype.getMeshByName = function (name) {
  26947. for (var index = 0; index < this.meshes.length; index++) {
  26948. if (this.meshes[index].name === name) {
  26949. return this.meshes[index];
  26950. }
  26951. }
  26952. return null;
  26953. };
  26954. /**
  26955. * Gets a transform node using a given name
  26956. * @param name defines the name to search for
  26957. * @return the found transform node or null if not found at all.
  26958. */
  26959. Scene.prototype.getTransformNodeByName = function (name) {
  26960. for (var index = 0; index < this.transformNodes.length; index++) {
  26961. if (this.transformNodes[index].name === name) {
  26962. return this.transformNodes[index];
  26963. }
  26964. }
  26965. return null;
  26966. };
  26967. /**
  26968. * Gets a sound using a given name
  26969. * @param name defines the name to search for
  26970. * @return the found sound or null if not found at all.
  26971. */
  26972. Scene.prototype.getSoundByName = function (name) {
  26973. var index;
  26974. if (BABYLON.AudioEngine) {
  26975. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26976. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26977. return this.mainSoundTrack.soundCollection[index];
  26978. }
  26979. }
  26980. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26981. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26982. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26983. return this.soundTracks[sdIndex].soundCollection[index];
  26984. }
  26985. }
  26986. }
  26987. }
  26988. return null;
  26989. };
  26990. /**
  26991. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26992. * @param id defines the id to search for
  26993. * @return the found skeleton or null if not found at all.
  26994. */
  26995. Scene.prototype.getLastSkeletonByID = function (id) {
  26996. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26997. if (this.skeletons[index].id === id) {
  26998. return this.skeletons[index];
  26999. }
  27000. }
  27001. return null;
  27002. };
  27003. /**
  27004. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27005. * @param id defines the id to search for
  27006. * @return the found skeleton or null if not found at all.
  27007. */
  27008. Scene.prototype.getSkeletonById = function (id) {
  27009. for (var index = 0; index < this.skeletons.length; index++) {
  27010. if (this.skeletons[index].id === id) {
  27011. return this.skeletons[index];
  27012. }
  27013. }
  27014. return null;
  27015. };
  27016. /**
  27017. * Gets a skeleton using a given name
  27018. * @param name defines the name to search for
  27019. * @return the found skeleton or null if not found at all.
  27020. */
  27021. Scene.prototype.getSkeletonByName = function (name) {
  27022. for (var index = 0; index < this.skeletons.length; index++) {
  27023. if (this.skeletons[index].name === name) {
  27024. return this.skeletons[index];
  27025. }
  27026. }
  27027. return null;
  27028. };
  27029. /**
  27030. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27031. * @param id defines the id to search for
  27032. * @return the found morph target manager or null if not found at all.
  27033. */
  27034. Scene.prototype.getMorphTargetManagerById = function (id) {
  27035. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27036. if (this.morphTargetManagers[index].uniqueId === id) {
  27037. return this.morphTargetManagers[index];
  27038. }
  27039. }
  27040. return null;
  27041. };
  27042. /**
  27043. * Gets a boolean indicating if the given mesh is active
  27044. * @param mesh defines the mesh to look for
  27045. * @returns true if the mesh is in the active list
  27046. */
  27047. Scene.prototype.isActiveMesh = function (mesh) {
  27048. return (this._activeMeshes.indexOf(mesh) !== -1);
  27049. };
  27050. /**
  27051. * Return a the first highlight layer of the scene with a given name.
  27052. * @param name The name of the highlight layer to look for.
  27053. * @return The highlight layer if found otherwise null.
  27054. */
  27055. Scene.prototype.getHighlightLayerByName = function (name) {
  27056. for (var index = 0; index < this.effectLayers.length; index++) {
  27057. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27058. return this.effectLayers[index];
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. /**
  27064. * Return a the first highlight layer of the scene with a given name.
  27065. * @param name The name of the highlight layer to look for.
  27066. * @return The highlight layer if found otherwise null.
  27067. */
  27068. Scene.prototype.getGlowLayerByName = function (name) {
  27069. for (var index = 0; index < this.effectLayers.length; index++) {
  27070. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27071. return this.effectLayers[index];
  27072. }
  27073. }
  27074. return null;
  27075. };
  27076. Object.defineProperty(Scene.prototype, "uid", {
  27077. /**
  27078. * Return a unique id as a string which can serve as an identifier for the scene
  27079. */
  27080. get: function () {
  27081. if (!this._uid) {
  27082. this._uid = BABYLON.Tools.RandomId();
  27083. }
  27084. return this._uid;
  27085. },
  27086. enumerable: true,
  27087. configurable: true
  27088. });
  27089. /**
  27090. * Add an externaly attached data from its key.
  27091. * This method call will fail and return false, if such key already exists.
  27092. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27093. * @param key the unique key that identifies the data
  27094. * @param data the data object to associate to the key for this Engine instance
  27095. * @return true if no such key were already present and the data was added successfully, false otherwise
  27096. */
  27097. Scene.prototype.addExternalData = function (key, data) {
  27098. if (!this._externalData) {
  27099. this._externalData = new BABYLON.StringDictionary();
  27100. }
  27101. return this._externalData.add(key, data);
  27102. };
  27103. /**
  27104. * Get an externaly attached data from its key
  27105. * @param key the unique key that identifies the data
  27106. * @return the associated data, if present (can be null), or undefined if not present
  27107. */
  27108. Scene.prototype.getExternalData = function (key) {
  27109. if (!this._externalData) {
  27110. return null;
  27111. }
  27112. return this._externalData.get(key);
  27113. };
  27114. /**
  27115. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27116. * @param key the unique key that identifies the data
  27117. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27118. * @return the associated data, can be null if the factory returned null.
  27119. */
  27120. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27121. if (!this._externalData) {
  27122. this._externalData = new BABYLON.StringDictionary();
  27123. }
  27124. return this._externalData.getOrAddWithFactory(key, factory);
  27125. };
  27126. /**
  27127. * Remove an externaly attached data from the Engine instance
  27128. * @param key the unique key that identifies the data
  27129. * @return true if the data was successfully removed, false if it doesn't exist
  27130. */
  27131. Scene.prototype.removeExternalData = function (key) {
  27132. return this._externalData.remove(key);
  27133. };
  27134. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27135. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27136. if (mesh.showSubMeshesBoundingBox) {
  27137. var boundingInfo = subMesh.getBoundingInfo();
  27138. if (boundingInfo !== null && boundingInfo !== undefined) {
  27139. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27140. }
  27141. }
  27142. var material = subMesh.getMaterial();
  27143. if (material !== null && material !== undefined) {
  27144. // Render targets
  27145. if (material.getRenderTargetTextures !== undefined) {
  27146. if (this._processedMaterials.indexOf(material) === -1) {
  27147. this._processedMaterials.push(material);
  27148. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27149. }
  27150. }
  27151. // Dispatch
  27152. this._activeIndices.addCount(subMesh.indexCount, false);
  27153. this._renderingManager.dispatch(subMesh, mesh, material);
  27154. }
  27155. }
  27156. };
  27157. /**
  27158. * Clear the processed materials smart array preventing retention point in material dispose.
  27159. */
  27160. Scene.prototype.freeProcessedMaterials = function () {
  27161. this._processedMaterials.dispose();
  27162. };
  27163. /**
  27164. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27165. */
  27166. Scene.prototype.freeActiveMeshes = function () {
  27167. this._activeMeshes.dispose();
  27168. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27169. this.activeCamera._activeMeshes.dispose();
  27170. }
  27171. if (this.activeCameras) {
  27172. for (var i = 0; i < this.activeCameras.length; i++) {
  27173. var activeCamera = this.activeCameras[i];
  27174. if (activeCamera && activeCamera._activeMeshes) {
  27175. activeCamera._activeMeshes.dispose();
  27176. }
  27177. }
  27178. }
  27179. };
  27180. /**
  27181. * Clear the info related to rendering groups preventing retention points during dispose.
  27182. */
  27183. Scene.prototype.freeRenderingGroups = function () {
  27184. if (this._renderingManager) {
  27185. this._renderingManager.freeRenderingGroups();
  27186. }
  27187. if (this.textures) {
  27188. for (var i = 0; i < this.textures.length; i++) {
  27189. var texture = this.textures[i];
  27190. if (texture && texture.renderList) {
  27191. texture.freeRenderingGroups();
  27192. }
  27193. }
  27194. }
  27195. };
  27196. /** @hidden */
  27197. Scene.prototype._isInIntermediateRendering = function () {
  27198. return this._intermediateRendering;
  27199. };
  27200. /**
  27201. * Defines the current active mesh candidate provider
  27202. * @param provider defines the provider to use
  27203. */
  27204. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27205. this._activeMeshCandidateProvider = provider;
  27206. };
  27207. /**
  27208. * Gets the current active mesh candidate provider
  27209. * @returns the current active mesh candidate provider
  27210. */
  27211. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27212. return this._activeMeshCandidateProvider;
  27213. };
  27214. /**
  27215. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27216. * @returns the current scene
  27217. */
  27218. Scene.prototype.freezeActiveMeshes = function () {
  27219. if (!this.activeCamera) {
  27220. return this;
  27221. }
  27222. if (!this._frustumPlanes) {
  27223. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27224. }
  27225. this._evaluateActiveMeshes();
  27226. this._activeMeshesFrozen = true;
  27227. return this;
  27228. };
  27229. /**
  27230. * Use this function to restart evaluating active meshes on every frame
  27231. * @returns the current scene
  27232. */
  27233. Scene.prototype.unfreezeActiveMeshes = function () {
  27234. this._activeMeshesFrozen = false;
  27235. return this;
  27236. };
  27237. Scene.prototype._evaluateActiveMeshes = function () {
  27238. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27239. return;
  27240. }
  27241. if (!this.activeCamera) {
  27242. return;
  27243. }
  27244. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27245. this.activeCamera._activeMeshes.reset();
  27246. this._activeMeshes.reset();
  27247. this._renderingManager.reset();
  27248. this._processedMaterials.reset();
  27249. this._activeParticleSystems.reset();
  27250. this._activeSkeletons.reset();
  27251. this._softwareSkinnedMeshes.reset();
  27252. if (this._boundingBoxRenderer) {
  27253. this._boundingBoxRenderer.reset();
  27254. }
  27255. // Meshes
  27256. var meshes;
  27257. var len;
  27258. var checkIsEnabled = true;
  27259. // Determine mesh candidates
  27260. if (this._activeMeshCandidateProvider !== undefined) {
  27261. // Use _activeMeshCandidateProvider
  27262. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27263. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27264. if (meshes !== undefined) {
  27265. len = meshes.length;
  27266. }
  27267. else {
  27268. len = 0;
  27269. }
  27270. }
  27271. else if (this._selectionOctree !== undefined) {
  27272. // Octree
  27273. var selection = this._selectionOctree.select(this._frustumPlanes);
  27274. meshes = selection.data;
  27275. len = selection.length;
  27276. }
  27277. else {
  27278. // Full scene traversal
  27279. len = this.meshes.length;
  27280. meshes = this.meshes;
  27281. }
  27282. // Check each mesh
  27283. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27284. mesh = meshes[meshIndex];
  27285. if (mesh.isBlocked) {
  27286. continue;
  27287. }
  27288. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27289. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27290. continue;
  27291. }
  27292. mesh.computeWorldMatrix();
  27293. // Intersections
  27294. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27295. this._meshesForIntersections.pushNoDuplicate(mesh);
  27296. }
  27297. // Switch to current LOD
  27298. meshLOD = mesh.getLOD(this.activeCamera);
  27299. if (meshLOD === undefined || meshLOD === null) {
  27300. continue;
  27301. }
  27302. mesh._preActivate();
  27303. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27304. this._activeMeshes.push(mesh);
  27305. this.activeCamera._activeMeshes.push(mesh);
  27306. mesh._activate(this._renderId);
  27307. if (meshLOD !== mesh) {
  27308. meshLOD._activate(this._renderId);
  27309. }
  27310. this._activeMesh(mesh, meshLOD);
  27311. }
  27312. }
  27313. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27314. // Particle systems
  27315. if (this.particlesEnabled) {
  27316. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27317. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27318. var particleSystem = this.particleSystems[particleIndex];
  27319. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27320. continue;
  27321. }
  27322. var emitter = particleSystem.emitter;
  27323. if (!emitter.position || emitter.isEnabled()) {
  27324. this._activeParticleSystems.push(particleSystem);
  27325. particleSystem.animate();
  27326. this._renderingManager.dispatchParticles(particleSystem);
  27327. }
  27328. }
  27329. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27330. }
  27331. };
  27332. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27333. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27334. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27335. mesh.skeleton.prepare();
  27336. }
  27337. if (!mesh.computeBonesUsingShaders) {
  27338. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27339. }
  27340. }
  27341. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27342. var boundingInfo = sourceMesh.getBoundingInfo();
  27343. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27344. }
  27345. if (mesh !== undefined && mesh !== null
  27346. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27347. // Submeshes Octrees
  27348. var len;
  27349. var subMeshes;
  27350. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27351. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27352. len = intersections.length;
  27353. subMeshes = intersections.data;
  27354. }
  27355. else {
  27356. subMeshes = mesh.subMeshes;
  27357. len = subMeshes.length;
  27358. }
  27359. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27360. subMesh = subMeshes[subIndex];
  27361. this._evaluateSubMesh(subMesh, mesh);
  27362. }
  27363. }
  27364. };
  27365. /**
  27366. * Update the transform matrix to update from the current active camera
  27367. * @param force defines a boolean used to force the update even if cache is up to date
  27368. */
  27369. Scene.prototype.updateTransformMatrix = function (force) {
  27370. if (!this.activeCamera) {
  27371. return;
  27372. }
  27373. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27374. };
  27375. /**
  27376. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27377. * @param alternateCamera defines the camera to use
  27378. */
  27379. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27380. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27381. };
  27382. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27383. if (camera && camera._skipRendering) {
  27384. return;
  27385. }
  27386. var engine = this._engine;
  27387. this.activeCamera = camera;
  27388. if (!this.activeCamera)
  27389. throw new Error("Active camera not set");
  27390. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27391. // Viewport
  27392. engine.setViewport(this.activeCamera.viewport);
  27393. // Camera
  27394. this.resetCachedMaterial();
  27395. this._renderId++;
  27396. this.updateTransformMatrix();
  27397. if (camera._alternateCamera) {
  27398. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27399. this._alternateRendering = true;
  27400. }
  27401. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27402. // Meshes
  27403. this._evaluateActiveMeshes();
  27404. // Software skinning
  27405. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27406. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27407. mesh.applySkeleton(mesh.skeleton);
  27408. }
  27409. // Render targets
  27410. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27411. var needsRestoreFrameBuffer = false;
  27412. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27413. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27414. }
  27415. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27416. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27417. }
  27418. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27419. this._intermediateRendering = true;
  27420. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27421. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27422. var renderTarget = this._renderTargets.data[renderIndex];
  27423. if (renderTarget._shouldRender()) {
  27424. this._renderId++;
  27425. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27426. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27427. }
  27428. }
  27429. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27430. this._intermediateRendering = false;
  27431. this._renderId++;
  27432. needsRestoreFrameBuffer = true; // Restore back buffer
  27433. }
  27434. // Render EffecttLayer Texture
  27435. var stencilState = this._engine.getStencilBuffer();
  27436. var renderEffects = false;
  27437. var needStencil = false;
  27438. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27439. this._intermediateRendering = true;
  27440. for (var i = 0; i < this.effectLayers.length; i++) {
  27441. var effectLayer = this.effectLayers[i];
  27442. if (effectLayer.shouldRender() &&
  27443. (!effectLayer.camera ||
  27444. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27445. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27446. renderEffects = true;
  27447. needStencil = needStencil || effectLayer.needStencil();
  27448. var renderTarget = effectLayer._mainTexture;
  27449. if (renderTarget._shouldRender()) {
  27450. this._renderId++;
  27451. renderTarget.render(false, false);
  27452. needsRestoreFrameBuffer = true;
  27453. }
  27454. }
  27455. }
  27456. this._intermediateRendering = false;
  27457. this._renderId++;
  27458. }
  27459. if (needsRestoreFrameBuffer) {
  27460. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27461. }
  27462. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27463. // Prepare Frame
  27464. this.postProcessManager._prepareFrame();
  27465. // Backgrounds
  27466. var layerIndex;
  27467. var layer;
  27468. if (this.layers.length) {
  27469. engine.setDepthBuffer(false);
  27470. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27471. layer = this.layers[layerIndex];
  27472. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27473. layer.render();
  27474. }
  27475. }
  27476. engine.setDepthBuffer(true);
  27477. }
  27478. // Activate effect Layer stencil
  27479. if (needStencil) {
  27480. this._engine.setStencilBuffer(true);
  27481. }
  27482. // Render
  27483. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27484. this._renderingManager.render(null, null, true, true);
  27485. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27486. // Restore effect Layer stencil
  27487. if (needStencil) {
  27488. this._engine.setStencilBuffer(stencilState);
  27489. }
  27490. // Bounding boxes
  27491. if (this._boundingBoxRenderer) {
  27492. this._boundingBoxRenderer.render();
  27493. }
  27494. // Lens flares
  27495. if (this.lensFlaresEnabled) {
  27496. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27497. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27498. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27499. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27500. lensFlareSystem.render();
  27501. }
  27502. }
  27503. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27504. }
  27505. // Effect Layer
  27506. if (renderEffects) {
  27507. engine.setDepthBuffer(false);
  27508. for (var i = 0; i < this.effectLayers.length; i++) {
  27509. if (this.effectLayers[i].shouldRender()) {
  27510. this.effectLayers[i].render();
  27511. }
  27512. }
  27513. engine.setDepthBuffer(true);
  27514. }
  27515. // Foregrounds
  27516. if (this.layers.length) {
  27517. engine.setDepthBuffer(false);
  27518. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27519. layer = this.layers[layerIndex];
  27520. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27521. layer.render();
  27522. }
  27523. }
  27524. engine.setDepthBuffer(true);
  27525. }
  27526. // Finalize frame
  27527. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27528. // Reset some special arrays
  27529. this._renderTargets.reset();
  27530. this._alternateRendering = false;
  27531. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27532. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27533. };
  27534. Scene.prototype._processSubCameras = function (camera) {
  27535. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27536. this._renderForCamera(camera);
  27537. return;
  27538. }
  27539. // rig cameras
  27540. for (var index = 0; index < camera._rigCameras.length; index++) {
  27541. this._renderForCamera(camera._rigCameras[index], camera);
  27542. }
  27543. this.activeCamera = camera;
  27544. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27545. };
  27546. Scene.prototype._checkIntersections = function () {
  27547. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27548. var sourceMesh = this._meshesForIntersections.data[index];
  27549. if (!sourceMesh.actionManager) {
  27550. continue;
  27551. }
  27552. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27553. var action = sourceMesh.actionManager.actions[actionIndex];
  27554. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27555. var parameters = action.getTriggerParameter();
  27556. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27557. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27558. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27559. if (areIntersecting && currentIntersectionInProgress === -1) {
  27560. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27561. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27562. sourceMesh._intersectionsInProgress.push(otherMesh);
  27563. }
  27564. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27565. sourceMesh._intersectionsInProgress.push(otherMesh);
  27566. }
  27567. }
  27568. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27569. //They intersected, and now they don't.
  27570. //is this trigger an exit trigger? execute an event.
  27571. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27572. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27573. }
  27574. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27575. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27576. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27577. return otherMesh === parameterMesh;
  27578. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27579. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27580. }
  27581. }
  27582. }
  27583. }
  27584. }
  27585. };
  27586. /**
  27587. * Render the scene
  27588. */
  27589. Scene.prototype.render = function () {
  27590. if (this.isDisposed) {
  27591. return;
  27592. }
  27593. this._activeParticles.fetchNewFrame();
  27594. this._totalVertices.fetchNewFrame();
  27595. this._activeIndices.fetchNewFrame();
  27596. this._activeBones.fetchNewFrame();
  27597. this._meshesForIntersections.reset();
  27598. this.resetCachedMaterial();
  27599. this.onBeforeAnimationsObservable.notifyObservers(this);
  27600. // Actions
  27601. if (this.actionManager) {
  27602. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27603. }
  27604. //Simplification Queue
  27605. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27606. this.simplificationQueue.executeNext();
  27607. }
  27608. if (this._engine.isDeterministicLockStep()) {
  27609. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27610. var defaultFPS = (60.0 / 1000.0);
  27611. var defaultFrameTime = 1000 / 60; // frame time in MS
  27612. if (this._physicsEngine) {
  27613. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27614. }
  27615. var stepsTaken = 0;
  27616. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27617. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27618. internalSteps = Math.min(internalSteps, maxSubSteps);
  27619. do {
  27620. this.onBeforeStepObservable.notifyObservers(this);
  27621. // Animations
  27622. this._animationRatio = defaultFrameTime * defaultFPS;
  27623. this._animate();
  27624. this.onAfterAnimationsObservable.notifyObservers(this);
  27625. // Physics
  27626. if (this._physicsEngine) {
  27627. this.onBeforePhysicsObservable.notifyObservers(this);
  27628. this._physicsEngine._step(defaultFrameTime / 1000);
  27629. this.onAfterPhysicsObservable.notifyObservers(this);
  27630. }
  27631. this.onAfterStepObservable.notifyObservers(this);
  27632. this._currentStepId++;
  27633. stepsTaken++;
  27634. deltaTime -= defaultFrameTime;
  27635. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27636. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27637. }
  27638. else {
  27639. // Animations
  27640. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27641. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27642. this._animate();
  27643. this.onAfterAnimationsObservable.notifyObservers(this);
  27644. // Physics
  27645. if (this._physicsEngine) {
  27646. this.onBeforePhysicsObservable.notifyObservers(this);
  27647. this._physicsEngine._step(deltaTime / 1000.0);
  27648. this.onAfterPhysicsObservable.notifyObservers(this);
  27649. }
  27650. }
  27651. // update gamepad manager
  27652. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27653. this._gamepadManager._checkGamepadsStatus();
  27654. }
  27655. // Update Cameras
  27656. if (this.activeCameras.length > 0) {
  27657. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27658. var camera = this.activeCameras[cameraIndex];
  27659. camera.update();
  27660. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27661. // rig cameras
  27662. for (var index = 0; index < camera._rigCameras.length; index++) {
  27663. camera._rigCameras[index].update();
  27664. }
  27665. }
  27666. }
  27667. }
  27668. else if (this.activeCamera) {
  27669. this.activeCamera.update();
  27670. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27671. // rig cameras
  27672. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27673. this.activeCamera._rigCameras[index].update();
  27674. }
  27675. }
  27676. }
  27677. // Before render
  27678. this.onBeforeRenderObservable.notifyObservers(this);
  27679. // Customs render targets
  27680. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27681. var engine = this.getEngine();
  27682. var currentActiveCamera = this.activeCamera;
  27683. if (this.renderTargetsEnabled) {
  27684. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27685. this._intermediateRendering = true;
  27686. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27687. var renderTarget = this.customRenderTargets[customIndex];
  27688. if (renderTarget._shouldRender()) {
  27689. this._renderId++;
  27690. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27691. if (!this.activeCamera)
  27692. throw new Error("Active camera not set");
  27693. // Viewport
  27694. engine.setViewport(this.activeCamera.viewport);
  27695. // Camera
  27696. this.updateTransformMatrix();
  27697. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27698. }
  27699. }
  27700. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27701. this._intermediateRendering = false;
  27702. this._renderId++;
  27703. }
  27704. // Restore back buffer
  27705. if (this.customRenderTargets.length > 0) {
  27706. engine.restoreDefaultFramebuffer();
  27707. }
  27708. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27709. this.activeCamera = currentActiveCamera;
  27710. // Procedural textures
  27711. if (this.proceduralTexturesEnabled) {
  27712. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27713. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27714. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27715. if (proceduralTexture._shouldRender()) {
  27716. proceduralTexture.render();
  27717. }
  27718. }
  27719. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27720. }
  27721. // Clear
  27722. if (this.autoClearDepthAndStencil || this.autoClear) {
  27723. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27724. }
  27725. // Shadows
  27726. if (this.shadowsEnabled) {
  27727. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27728. var light = this.lights[lightIndex];
  27729. var shadowGenerator = light.getShadowGenerator();
  27730. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27731. var shadowMap = (shadowGenerator.getShadowMap());
  27732. if (this.textures.indexOf(shadowMap) !== -1) {
  27733. this._renderTargets.push(shadowMap);
  27734. }
  27735. }
  27736. }
  27737. }
  27738. // Depth renderer
  27739. for (var key in this._depthRenderer) {
  27740. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27741. }
  27742. // Geometry renderer
  27743. if (this._geometryBufferRenderer) {
  27744. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27745. }
  27746. // RenderPipeline
  27747. if (this._postProcessRenderPipelineManager) {
  27748. this._postProcessRenderPipelineManager.update();
  27749. }
  27750. // Multi-cameras?
  27751. if (this.activeCameras.length > 0) {
  27752. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27753. if (cameraIndex > 0) {
  27754. this._engine.clear(null, false, true, true);
  27755. }
  27756. this._processSubCameras(this.activeCameras[cameraIndex]);
  27757. }
  27758. }
  27759. else {
  27760. if (!this.activeCamera) {
  27761. throw new Error("No camera defined");
  27762. }
  27763. this._processSubCameras(this.activeCamera);
  27764. }
  27765. // Intersection checks
  27766. this._checkIntersections();
  27767. // Update the audio listener attached to the camera
  27768. if (BABYLON.AudioEngine) {
  27769. this._updateAudioParameters();
  27770. }
  27771. // After render
  27772. if (this.afterRender) {
  27773. this.afterRender();
  27774. }
  27775. this.onAfterRenderObservable.notifyObservers(this);
  27776. // Cleaning
  27777. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27778. var data = this._toBeDisposed.data[index];
  27779. if (data) {
  27780. data.dispose();
  27781. }
  27782. this._toBeDisposed[index] = null;
  27783. }
  27784. this._toBeDisposed.reset();
  27785. if (this.dumpNextRenderTargets) {
  27786. this.dumpNextRenderTargets = false;
  27787. }
  27788. this._activeBones.addCount(0, true);
  27789. this._activeIndices.addCount(0, true);
  27790. this._activeParticles.addCount(0, true);
  27791. };
  27792. Scene.prototype._updateAudioParameters = function () {
  27793. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27794. return;
  27795. }
  27796. var listeningCamera;
  27797. var audioEngine = BABYLON.Engine.audioEngine;
  27798. if (this.activeCameras.length > 0) {
  27799. listeningCamera = this.activeCameras[0];
  27800. }
  27801. else {
  27802. listeningCamera = this.activeCamera;
  27803. }
  27804. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27805. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27806. // for VR cameras
  27807. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27808. listeningCamera = listeningCamera.rigCameras[0];
  27809. }
  27810. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27811. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27812. cameraDirection.normalize();
  27813. // To avoid some errors on GearVR
  27814. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27815. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27816. }
  27817. var i;
  27818. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27819. var sound = this.mainSoundTrack.soundCollection[i];
  27820. if (sound.useCustomAttenuation) {
  27821. sound.updateDistanceFromListener();
  27822. }
  27823. }
  27824. for (i = 0; i < this.soundTracks.length; i++) {
  27825. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27826. sound = this.soundTracks[i].soundCollection[j];
  27827. if (sound.useCustomAttenuation) {
  27828. sound.updateDistanceFromListener();
  27829. }
  27830. }
  27831. }
  27832. }
  27833. };
  27834. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27835. // Audio
  27836. /**
  27837. * Gets or sets if audio support is enabled
  27838. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27839. */
  27840. get: function () {
  27841. return this._audioEnabled;
  27842. },
  27843. set: function (value) {
  27844. this._audioEnabled = value;
  27845. if (BABYLON.AudioEngine) {
  27846. if (this._audioEnabled) {
  27847. this._enableAudio();
  27848. }
  27849. else {
  27850. this._disableAudio();
  27851. }
  27852. }
  27853. },
  27854. enumerable: true,
  27855. configurable: true
  27856. });
  27857. Scene.prototype._disableAudio = function () {
  27858. var i;
  27859. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27860. this.mainSoundTrack.soundCollection[i].pause();
  27861. }
  27862. for (i = 0; i < this.soundTracks.length; i++) {
  27863. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27864. this.soundTracks[i].soundCollection[j].pause();
  27865. }
  27866. }
  27867. };
  27868. Scene.prototype._enableAudio = function () {
  27869. var i;
  27870. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27871. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27872. this.mainSoundTrack.soundCollection[i].play();
  27873. }
  27874. }
  27875. for (i = 0; i < this.soundTracks.length; i++) {
  27876. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27877. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27878. this.soundTracks[i].soundCollection[j].play();
  27879. }
  27880. }
  27881. }
  27882. };
  27883. Object.defineProperty(Scene.prototype, "headphone", {
  27884. /**
  27885. * Gets or sets if audio will be output to headphones
  27886. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27887. */
  27888. get: function () {
  27889. return this._headphone;
  27890. },
  27891. set: function (value) {
  27892. this._headphone = value;
  27893. if (BABYLON.AudioEngine) {
  27894. if (this._headphone) {
  27895. this._switchAudioModeForHeadphones();
  27896. }
  27897. else {
  27898. this._switchAudioModeForNormalSpeakers();
  27899. }
  27900. }
  27901. },
  27902. enumerable: true,
  27903. configurable: true
  27904. });
  27905. Scene.prototype._switchAudioModeForHeadphones = function () {
  27906. this.mainSoundTrack.switchPanningModelToHRTF();
  27907. for (var i = 0; i < this.soundTracks.length; i++) {
  27908. this.soundTracks[i].switchPanningModelToHRTF();
  27909. }
  27910. };
  27911. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27912. this.mainSoundTrack.switchPanningModelToEqualPower();
  27913. for (var i = 0; i < this.soundTracks.length; i++) {
  27914. this.soundTracks[i].switchPanningModelToEqualPower();
  27915. }
  27916. };
  27917. /**
  27918. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27919. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27920. * @returns the created depth renderer
  27921. */
  27922. Scene.prototype.enableDepthRenderer = function (camera) {
  27923. camera = camera || this.activeCamera;
  27924. if (!camera) {
  27925. throw "No camera available to enable depth renderer";
  27926. }
  27927. if (!this._depthRenderer[camera.id]) {
  27928. var textureType = 0;
  27929. if (this._engine.getCaps().textureHalfFloatRender) {
  27930. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27931. }
  27932. else if (this._engine.getCaps().textureFloatRender) {
  27933. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27934. }
  27935. else {
  27936. throw "Depth renderer does not support int texture type";
  27937. }
  27938. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27939. }
  27940. return this._depthRenderer[camera.id];
  27941. };
  27942. /**
  27943. * Disables a depth renderer for a given camera
  27944. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27945. */
  27946. Scene.prototype.disableDepthRenderer = function (camera) {
  27947. camera = camera || this.activeCamera;
  27948. if (!camera || !this._depthRenderer[camera.id]) {
  27949. return;
  27950. }
  27951. this._depthRenderer[camera.id].dispose();
  27952. delete this._depthRenderer[camera.id];
  27953. };
  27954. /**
  27955. * Enables a GeometryBufferRender and associates it with the scene
  27956. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27957. * @returns the GeometryBufferRenderer
  27958. */
  27959. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27960. if (ratio === void 0) { ratio = 1; }
  27961. if (this._geometryBufferRenderer) {
  27962. return this._geometryBufferRenderer;
  27963. }
  27964. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27965. if (!this._geometryBufferRenderer.isSupported) {
  27966. this._geometryBufferRenderer = null;
  27967. }
  27968. return this._geometryBufferRenderer;
  27969. };
  27970. /**
  27971. * Disables the GeometryBufferRender associated with the scene
  27972. */
  27973. Scene.prototype.disableGeometryBufferRenderer = function () {
  27974. if (!this._geometryBufferRenderer) {
  27975. return;
  27976. }
  27977. this._geometryBufferRenderer.dispose();
  27978. this._geometryBufferRenderer = null;
  27979. };
  27980. /**
  27981. * Freeze all materials
  27982. * A frozen material will not be updatable but should be faster to render
  27983. */
  27984. Scene.prototype.freezeMaterials = function () {
  27985. for (var i = 0; i < this.materials.length; i++) {
  27986. this.materials[i].freeze();
  27987. }
  27988. };
  27989. /**
  27990. * Unfreeze all materials
  27991. * A frozen material will not be updatable but should be faster to render
  27992. */
  27993. Scene.prototype.unfreezeMaterials = function () {
  27994. for (var i = 0; i < this.materials.length; i++) {
  27995. this.materials[i].unfreeze();
  27996. }
  27997. };
  27998. /**
  27999. * Releases all held ressources
  28000. */
  28001. Scene.prototype.dispose = function () {
  28002. this.beforeRender = null;
  28003. this.afterRender = null;
  28004. this.skeletons = [];
  28005. this.morphTargetManagers = [];
  28006. this.importedMeshesFiles = new Array();
  28007. this.stopAllAnimations();
  28008. this.resetCachedMaterial();
  28009. for (var key in this._depthRenderer) {
  28010. this._depthRenderer[key].dispose();
  28011. }
  28012. if (this._gamepadManager) {
  28013. this._gamepadManager.dispose();
  28014. this._gamepadManager = null;
  28015. }
  28016. // Smart arrays
  28017. if (this.activeCamera) {
  28018. this.activeCamera._activeMeshes.dispose();
  28019. this.activeCamera = null;
  28020. }
  28021. this._activeMeshes.dispose();
  28022. this._renderingManager.dispose();
  28023. this._processedMaterials.dispose();
  28024. this._activeParticleSystems.dispose();
  28025. this._activeSkeletons.dispose();
  28026. this._softwareSkinnedMeshes.dispose();
  28027. this._renderTargets.dispose();
  28028. this._registeredForLateAnimationBindings.dispose();
  28029. if (this._boundingBoxRenderer) {
  28030. this._boundingBoxRenderer.dispose();
  28031. }
  28032. this._meshesForIntersections.dispose();
  28033. this._toBeDisposed.dispose();
  28034. // Abort active requests
  28035. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28036. var request = _a[_i];
  28037. request.abort();
  28038. }
  28039. // Debug layer
  28040. if (this._debugLayer) {
  28041. this._debugLayer.hide();
  28042. }
  28043. // Events
  28044. this.onDisposeObservable.notifyObservers(this);
  28045. this.onDisposeObservable.clear();
  28046. this.onBeforeRenderObservable.clear();
  28047. this.onAfterRenderObservable.clear();
  28048. this.onBeforeRenderTargetsRenderObservable.clear();
  28049. this.onAfterRenderTargetsRenderObservable.clear();
  28050. this.onAfterStepObservable.clear();
  28051. this.onBeforeStepObservable.clear();
  28052. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28053. this.onAfterActiveMeshesEvaluationObservable.clear();
  28054. this.onBeforeParticlesRenderingObservable.clear();
  28055. this.onAfterParticlesRenderingObservable.clear();
  28056. this.onBeforeSpritesRenderingObservable.clear();
  28057. this.onAfterSpritesRenderingObservable.clear();
  28058. this.onBeforeDrawPhaseObservable.clear();
  28059. this.onAfterDrawPhaseObservable.clear();
  28060. this.onBeforePhysicsObservable.clear();
  28061. this.onAfterPhysicsObservable.clear();
  28062. this.onBeforeAnimationsObservable.clear();
  28063. this.onAfterAnimationsObservable.clear();
  28064. this.onDataLoadedObservable.clear();
  28065. this.detachControl();
  28066. // Release sounds & sounds tracks
  28067. if (BABYLON.AudioEngine) {
  28068. this.disposeSounds();
  28069. }
  28070. // VR Helper
  28071. if (this.VRHelper) {
  28072. this.VRHelper.dispose();
  28073. }
  28074. // Detach cameras
  28075. var canvas = this._engine.getRenderingCanvas();
  28076. if (canvas) {
  28077. var index;
  28078. for (index = 0; index < this.cameras.length; index++) {
  28079. this.cameras[index].detachControl(canvas);
  28080. }
  28081. }
  28082. // Release animation groups
  28083. while (this.animationGroups.length) {
  28084. this.animationGroups[0].dispose();
  28085. }
  28086. // Release lights
  28087. while (this.lights.length) {
  28088. this.lights[0].dispose();
  28089. }
  28090. // Release meshes
  28091. while (this.meshes.length) {
  28092. this.meshes[0].dispose(true);
  28093. }
  28094. while (this.transformNodes.length) {
  28095. this.removeTransformNode(this.transformNodes[0]);
  28096. }
  28097. // Release cameras
  28098. while (this.cameras.length) {
  28099. this.cameras[0].dispose();
  28100. }
  28101. // Release materials
  28102. if (this.defaultMaterial) {
  28103. this.defaultMaterial.dispose();
  28104. }
  28105. while (this.multiMaterials.length) {
  28106. this.multiMaterials[0].dispose();
  28107. }
  28108. while (this.materials.length) {
  28109. this.materials[0].dispose();
  28110. }
  28111. // Release particles
  28112. while (this.particleSystems.length) {
  28113. this.particleSystems[0].dispose();
  28114. }
  28115. // Release sprites
  28116. while (this.spriteManagers.length) {
  28117. this.spriteManagers[0].dispose();
  28118. }
  28119. // Release postProcesses
  28120. while (this.postProcesses.length) {
  28121. this.postProcesses[0].dispose();
  28122. }
  28123. // Release layers
  28124. while (this.layers.length) {
  28125. this.layers[0].dispose();
  28126. }
  28127. while (this.effectLayers.length) {
  28128. this.effectLayers[0].dispose();
  28129. }
  28130. // Release textures
  28131. while (this.textures.length) {
  28132. this.textures[0].dispose();
  28133. }
  28134. // Release UBO
  28135. this._sceneUbo.dispose();
  28136. if (this._alternateSceneUbo) {
  28137. this._alternateSceneUbo.dispose();
  28138. }
  28139. // Post-processes
  28140. this.postProcessManager.dispose();
  28141. if (this._postProcessRenderPipelineManager) {
  28142. this._postProcessRenderPipelineManager.dispose();
  28143. }
  28144. // Physics
  28145. if (this._physicsEngine) {
  28146. this.disablePhysicsEngine();
  28147. }
  28148. // Remove from engine
  28149. index = this._engine.scenes.indexOf(this);
  28150. if (index > -1) {
  28151. this._engine.scenes.splice(index, 1);
  28152. }
  28153. this._engine.wipeCaches(true);
  28154. this._isDisposed = true;
  28155. };
  28156. Object.defineProperty(Scene.prototype, "isDisposed", {
  28157. /**
  28158. * Gets if the scene is already disposed
  28159. */
  28160. get: function () {
  28161. return this._isDisposed;
  28162. },
  28163. enumerable: true,
  28164. configurable: true
  28165. });
  28166. /**
  28167. * Releases sounds & soundtracks
  28168. */
  28169. Scene.prototype.disposeSounds = function () {
  28170. if (!this._mainSoundTrack) {
  28171. return;
  28172. }
  28173. this.mainSoundTrack.dispose();
  28174. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28175. this.soundTracks[scIndex].dispose();
  28176. }
  28177. };
  28178. // Octrees
  28179. /**
  28180. * Get the world extend vectors with an optional filter
  28181. *
  28182. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28183. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28184. */
  28185. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28186. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28187. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28188. filterPredicate = filterPredicate || (function () { return true; });
  28189. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28190. mesh.computeWorldMatrix(true);
  28191. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28192. return;
  28193. }
  28194. var boundingInfo = mesh.getBoundingInfo();
  28195. var minBox = boundingInfo.boundingBox.minimumWorld;
  28196. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28197. BABYLON.Tools.CheckExtends(minBox, min, max);
  28198. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28199. });
  28200. return {
  28201. min: min,
  28202. max: max
  28203. };
  28204. };
  28205. /**
  28206. * Creates or updates the octree used to boost selection (picking)
  28207. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28208. * @param maxCapacity defines the maximum capacity per leaf
  28209. * @param maxDepth defines the maximum depth of the octree
  28210. * @returns an octree of AbstractMesh
  28211. */
  28212. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28213. if (maxCapacity === void 0) { maxCapacity = 64; }
  28214. if (maxDepth === void 0) { maxDepth = 2; }
  28215. if (!this._selectionOctree) {
  28216. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28217. }
  28218. var worldExtends = this.getWorldExtends();
  28219. // Update octree
  28220. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28221. return this._selectionOctree;
  28222. };
  28223. // Picking
  28224. /**
  28225. * Creates a ray that can be used to pick in the scene
  28226. * @param x defines the x coordinate of the origin (on-screen)
  28227. * @param y defines the y coordinate of the origin (on-screen)
  28228. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28229. * @param camera defines the camera to use for the picking
  28230. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28231. * @returns a Ray
  28232. */
  28233. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28234. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28235. var result = BABYLON.Ray.Zero();
  28236. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28237. return result;
  28238. };
  28239. /**
  28240. * Creates a ray that can be used to pick in the scene
  28241. * @param x defines the x coordinate of the origin (on-screen)
  28242. * @param y defines the y coordinate of the origin (on-screen)
  28243. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28244. * @param result defines the ray where to store the picking ray
  28245. * @param camera defines the camera to use for the picking
  28246. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28247. * @returns the current scene
  28248. */
  28249. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28250. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28251. var engine = this._engine;
  28252. if (!camera) {
  28253. if (!this.activeCamera)
  28254. throw new Error("Active camera not set");
  28255. camera = this.activeCamera;
  28256. }
  28257. var cameraViewport = camera.viewport;
  28258. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28259. // Moving coordinates to local viewport world
  28260. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28261. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28262. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28263. return this;
  28264. };
  28265. /**
  28266. * Creates a ray that can be used to pick in the scene
  28267. * @param x defines the x coordinate of the origin (on-screen)
  28268. * @param y defines the y coordinate of the origin (on-screen)
  28269. * @param camera defines the camera to use for the picking
  28270. * @returns a Ray
  28271. */
  28272. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28273. var result = BABYLON.Ray.Zero();
  28274. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28275. return result;
  28276. };
  28277. /**
  28278. * Creates a ray that can be used to pick in the scene
  28279. * @param x defines the x coordinate of the origin (on-screen)
  28280. * @param y defines the y coordinate of the origin (on-screen)
  28281. * @param result defines the ray where to store the picking ray
  28282. * @param camera defines the camera to use for the picking
  28283. * @returns the current scene
  28284. */
  28285. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28286. if (!BABYLON.PickingInfo) {
  28287. return this;
  28288. }
  28289. var engine = this._engine;
  28290. if (!camera) {
  28291. if (!this.activeCamera)
  28292. throw new Error("Active camera not set");
  28293. camera = this.activeCamera;
  28294. }
  28295. var cameraViewport = camera.viewport;
  28296. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28297. var identity = BABYLON.Matrix.Identity();
  28298. // Moving coordinates to local viewport world
  28299. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28300. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28301. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28302. return this;
  28303. };
  28304. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28305. if (!BABYLON.PickingInfo) {
  28306. return null;
  28307. }
  28308. var pickingInfo = null;
  28309. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28310. var mesh = this.meshes[meshIndex];
  28311. if (predicate) {
  28312. if (!predicate(mesh)) {
  28313. continue;
  28314. }
  28315. }
  28316. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28317. continue;
  28318. }
  28319. var world = mesh.getWorldMatrix();
  28320. var ray = rayFunction(world);
  28321. var result = mesh.intersects(ray, fastCheck);
  28322. if (!result || !result.hit)
  28323. continue;
  28324. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28325. continue;
  28326. pickingInfo = result;
  28327. if (fastCheck) {
  28328. break;
  28329. }
  28330. }
  28331. return pickingInfo || new BABYLON.PickingInfo();
  28332. };
  28333. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28334. if (!BABYLON.PickingInfo) {
  28335. return null;
  28336. }
  28337. var pickingInfos = new Array();
  28338. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28339. var mesh = this.meshes[meshIndex];
  28340. if (predicate) {
  28341. if (!predicate(mesh)) {
  28342. continue;
  28343. }
  28344. }
  28345. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28346. continue;
  28347. }
  28348. var world = mesh.getWorldMatrix();
  28349. var ray = rayFunction(world);
  28350. var result = mesh.intersects(ray, false);
  28351. if (!result || !result.hit)
  28352. continue;
  28353. pickingInfos.push(result);
  28354. }
  28355. return pickingInfos;
  28356. };
  28357. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28358. if (!BABYLON.PickingInfo) {
  28359. return null;
  28360. }
  28361. var pickingInfo = null;
  28362. if (!camera) {
  28363. if (!this.activeCamera) {
  28364. return null;
  28365. }
  28366. camera = this.activeCamera;
  28367. }
  28368. if (this.spriteManagers.length > 0) {
  28369. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28370. var spriteManager = this.spriteManagers[spriteIndex];
  28371. if (!spriteManager.isPickable) {
  28372. continue;
  28373. }
  28374. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28375. if (!result || !result.hit)
  28376. continue;
  28377. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28378. continue;
  28379. pickingInfo = result;
  28380. if (fastCheck) {
  28381. break;
  28382. }
  28383. }
  28384. }
  28385. return pickingInfo || new BABYLON.PickingInfo();
  28386. };
  28387. /** Launch a ray to try to pick a mesh in the scene
  28388. * @param x position on screen
  28389. * @param y position on screen
  28390. * @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
  28391. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28392. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28393. * @returns a PickingInfo
  28394. */
  28395. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28396. var _this = this;
  28397. if (!BABYLON.PickingInfo) {
  28398. return null;
  28399. }
  28400. return this._internalPick(function (world) {
  28401. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28402. return _this._tempPickingRay;
  28403. }, predicate, fastCheck);
  28404. };
  28405. /** Launch a ray to try to pick a sprite in the scene
  28406. * @param x position on screen
  28407. * @param y position on screen
  28408. * @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
  28409. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28410. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28411. * @returns a PickingInfo
  28412. */
  28413. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28414. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28415. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28416. };
  28417. /** Use the given ray to pick a mesh in the scene
  28418. * @param ray The ray to use to pick meshes
  28419. * @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
  28420. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28421. * @returns a PickingInfo
  28422. */
  28423. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28424. var _this = this;
  28425. return this._internalPick(function (world) {
  28426. if (!_this._pickWithRayInverseMatrix) {
  28427. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28428. }
  28429. world.invertToRef(_this._pickWithRayInverseMatrix);
  28430. if (!_this._cachedRayForTransform) {
  28431. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28432. }
  28433. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28434. return _this._cachedRayForTransform;
  28435. }, predicate, fastCheck);
  28436. };
  28437. /**
  28438. * Launch a ray to try to pick a mesh in the scene
  28439. * @param x X position on screen
  28440. * @param y Y position on screen
  28441. * @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
  28442. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28443. * @returns an array of PickingInfo
  28444. */
  28445. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28446. var _this = this;
  28447. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28448. };
  28449. /**
  28450. * Launch a ray to try to pick a mesh in the scene
  28451. * @param ray Ray to use
  28452. * @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
  28453. * @returns an array of PickingInfo
  28454. */
  28455. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28456. var _this = this;
  28457. return this._internalMultiPick(function (world) {
  28458. if (!_this._pickWithRayInverseMatrix) {
  28459. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28460. }
  28461. world.invertToRef(_this._pickWithRayInverseMatrix);
  28462. if (!_this._cachedRayForTransform) {
  28463. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28464. }
  28465. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28466. return _this._cachedRayForTransform;
  28467. }, predicate);
  28468. };
  28469. /**
  28470. * Force the value of meshUnderPointer
  28471. * @param mesh defines the mesh to use
  28472. */
  28473. Scene.prototype.setPointerOverMesh = function (mesh) {
  28474. if (this._pointerOverMesh === mesh) {
  28475. return;
  28476. }
  28477. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28478. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28479. }
  28480. this._pointerOverMesh = mesh;
  28481. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28482. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28483. }
  28484. };
  28485. /**
  28486. * Gets the mesh under the pointer
  28487. * @returns a Mesh or null if no mesh is under the pointer
  28488. */
  28489. Scene.prototype.getPointerOverMesh = function () {
  28490. return this._pointerOverMesh;
  28491. };
  28492. /**
  28493. * Force the sprite under the pointer
  28494. * @param sprite defines the sprite to use
  28495. */
  28496. Scene.prototype.setPointerOverSprite = function (sprite) {
  28497. if (this._pointerOverSprite === sprite) {
  28498. return;
  28499. }
  28500. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28501. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28502. }
  28503. this._pointerOverSprite = sprite;
  28504. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28505. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28506. }
  28507. };
  28508. /**
  28509. * Gets the sprite under the pointer
  28510. * @returns a Sprite or null if no sprite is under the pointer
  28511. */
  28512. Scene.prototype.getPointerOverSprite = function () {
  28513. return this._pointerOverSprite;
  28514. };
  28515. // Physics
  28516. /**
  28517. * Gets the current physics engine
  28518. * @returns a PhysicsEngine or null if none attached
  28519. */
  28520. Scene.prototype.getPhysicsEngine = function () {
  28521. return this._physicsEngine;
  28522. };
  28523. /**
  28524. * Enables physics to the current scene
  28525. * @param gravity defines the scene's gravity for the physics engine
  28526. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28527. * @return a boolean indicating if the physics engine was initialized
  28528. */
  28529. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28530. if (gravity === void 0) { gravity = null; }
  28531. if (this._physicsEngine) {
  28532. return true;
  28533. }
  28534. try {
  28535. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28536. return true;
  28537. }
  28538. catch (e) {
  28539. BABYLON.Tools.Error(e.message);
  28540. return false;
  28541. }
  28542. };
  28543. /**
  28544. * Disables and disposes the physics engine associated with the scene
  28545. */
  28546. Scene.prototype.disablePhysicsEngine = function () {
  28547. if (!this._physicsEngine) {
  28548. return;
  28549. }
  28550. this._physicsEngine.dispose();
  28551. this._physicsEngine = null;
  28552. };
  28553. /**
  28554. * Gets a boolean indicating if there is an active physics engine
  28555. * @returns a boolean indicating if there is an active physics engine
  28556. */
  28557. Scene.prototype.isPhysicsEnabled = function () {
  28558. return this._physicsEngine !== undefined;
  28559. };
  28560. /**
  28561. * Deletes a physics compound impostor
  28562. * @param compound defines the compound to delete
  28563. */
  28564. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28565. var mesh = compound.parts[0].mesh;
  28566. if (mesh.physicsImpostor) {
  28567. mesh.physicsImpostor.dispose( /*true*/);
  28568. mesh.physicsImpostor = null;
  28569. }
  28570. };
  28571. // Misc.
  28572. /** @hidden */
  28573. Scene.prototype._rebuildGeometries = function () {
  28574. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28575. var geometry = _a[_i];
  28576. geometry._rebuild();
  28577. }
  28578. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28579. var mesh = _c[_b];
  28580. mesh._rebuild();
  28581. }
  28582. if (this.postProcessManager) {
  28583. this.postProcessManager._rebuild();
  28584. }
  28585. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28586. var layer = _e[_d];
  28587. layer._rebuild();
  28588. }
  28589. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28590. var effectLayer = _g[_f];
  28591. effectLayer._rebuild();
  28592. }
  28593. if (this._boundingBoxRenderer) {
  28594. this._boundingBoxRenderer._rebuild();
  28595. }
  28596. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28597. var system = _j[_h];
  28598. system.rebuild();
  28599. }
  28600. if (this._postProcessRenderPipelineManager) {
  28601. this._postProcessRenderPipelineManager._rebuild();
  28602. }
  28603. };
  28604. /** @hidden */
  28605. Scene.prototype._rebuildTextures = function () {
  28606. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28607. var texture = _a[_i];
  28608. texture._rebuild();
  28609. }
  28610. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28611. };
  28612. /**
  28613. * Creates a default light for the scene.
  28614. * @param replace Whether to replace the existing lights in the scene.
  28615. */
  28616. Scene.prototype.createDefaultLight = function (replace) {
  28617. if (replace === void 0) { replace = false; }
  28618. // Dispose existing light in replace mode.
  28619. if (replace) {
  28620. if (this.lights) {
  28621. for (var i = 0; i < this.lights.length; i++) {
  28622. this.lights[i].dispose();
  28623. }
  28624. }
  28625. }
  28626. // Light
  28627. if (this.lights.length === 0) {
  28628. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28629. }
  28630. };
  28631. /**
  28632. * Creates a default camera for the scene.
  28633. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28634. * @param replace Whether to replace the existing active camera in the scene.
  28635. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28636. */
  28637. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28638. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28639. if (replace === void 0) { replace = false; }
  28640. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28641. // Dispose existing camera in replace mode.
  28642. if (replace) {
  28643. if (this.activeCamera) {
  28644. this.activeCamera.dispose();
  28645. this.activeCamera = null;
  28646. }
  28647. }
  28648. // Camera
  28649. if (!this.activeCamera) {
  28650. var worldExtends = this.getWorldExtends();
  28651. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28652. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28653. var camera;
  28654. var radius = worldSize.length() * 1.5;
  28655. // empty scene scenario!
  28656. if (!isFinite(radius)) {
  28657. radius = 1;
  28658. worldCenter.copyFromFloats(0, 0, 0);
  28659. }
  28660. if (createArcRotateCamera) {
  28661. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28662. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28663. arcRotateCamera.wheelPrecision = 100 / radius;
  28664. camera = arcRotateCamera;
  28665. }
  28666. else {
  28667. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28668. freeCamera.setTarget(worldCenter);
  28669. camera = freeCamera;
  28670. }
  28671. camera.minZ = radius * 0.01;
  28672. camera.maxZ = radius * 1000;
  28673. camera.speed = radius * 0.2;
  28674. this.activeCamera = camera;
  28675. var canvas = this.getEngine().getRenderingCanvas();
  28676. if (attachCameraControls && canvas) {
  28677. camera.attachControl(canvas);
  28678. }
  28679. }
  28680. };
  28681. /**
  28682. * Creates a default camera and a default light
  28683. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28684. * @param replace defines if the camera and/or light will replace the existing ones
  28685. * @param attachCameraControls defines if attachControl will be called on the new camera
  28686. */
  28687. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28688. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28689. if (replace === void 0) { replace = false; }
  28690. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28691. this.createDefaultLight(replace);
  28692. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28693. };
  28694. /**
  28695. * Creates a new sky box
  28696. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28697. * @param environmentTexture defines the texture to use as environment texture
  28698. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28699. * @param scale defines the overall scale of the skybox
  28700. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28701. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28702. * @returns a new mesh holding the sky box
  28703. */
  28704. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28705. if (pbr === void 0) { pbr = false; }
  28706. if (scale === void 0) { scale = 1000; }
  28707. if (blur === void 0) { blur = 0; }
  28708. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28709. if (!environmentTexture) {
  28710. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28711. return null;
  28712. }
  28713. if (setGlobalEnvTexture) {
  28714. if (environmentTexture) {
  28715. this.environmentTexture = environmentTexture;
  28716. }
  28717. }
  28718. // Skybox
  28719. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28720. if (pbr) {
  28721. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28722. hdrSkyboxMaterial.backFaceCulling = false;
  28723. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28724. if (hdrSkyboxMaterial.reflectionTexture) {
  28725. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28726. }
  28727. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28728. hdrSkyboxMaterial.disableLighting = true;
  28729. hdrSkyboxMaterial.twoSidedLighting = true;
  28730. hdrSkybox.infiniteDistance = true;
  28731. hdrSkybox.material = hdrSkyboxMaterial;
  28732. }
  28733. else {
  28734. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28735. skyboxMaterial.backFaceCulling = false;
  28736. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28737. if (skyboxMaterial.reflectionTexture) {
  28738. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28739. }
  28740. skyboxMaterial.disableLighting = true;
  28741. hdrSkybox.infiniteDistance = true;
  28742. hdrSkybox.material = skyboxMaterial;
  28743. }
  28744. return hdrSkybox;
  28745. };
  28746. /**
  28747. * Creates a new environment
  28748. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28749. * @param options defines the options you can use to configure the environment
  28750. * @returns the new EnvironmentHelper
  28751. */
  28752. Scene.prototype.createDefaultEnvironment = function (options) {
  28753. if (BABYLON.EnvironmentHelper) {
  28754. return new BABYLON.EnvironmentHelper(options, this);
  28755. }
  28756. return null;
  28757. };
  28758. /**
  28759. * Creates a new VREXperienceHelper
  28760. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28761. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28762. * @returns a new VREXperienceHelper
  28763. */
  28764. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28765. if (webVROptions === void 0) { webVROptions = {}; }
  28766. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28767. };
  28768. // Tags
  28769. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28770. if (tagsQuery === undefined) {
  28771. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28772. return list;
  28773. }
  28774. var listByTags = [];
  28775. forEach = forEach || (function (item) { return; });
  28776. for (var i in list) {
  28777. var item = list[i];
  28778. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28779. listByTags.push(item);
  28780. forEach(item);
  28781. }
  28782. }
  28783. return listByTags;
  28784. };
  28785. /**
  28786. * Get a list of meshes by tags
  28787. * @param tagsQuery defines the tags query to use
  28788. * @param forEach defines a predicate used to filter results
  28789. * @returns an array of Mesh
  28790. */
  28791. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28792. return this._getByTags(this.meshes, tagsQuery, forEach);
  28793. };
  28794. /**
  28795. * Get a list of cameras by tags
  28796. * @param tagsQuery defines the tags query to use
  28797. * @param forEach defines a predicate used to filter results
  28798. * @returns an array of Camera
  28799. */
  28800. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28801. return this._getByTags(this.cameras, tagsQuery, forEach);
  28802. };
  28803. /**
  28804. * Get a list of lights by tags
  28805. * @param tagsQuery defines the tags query to use
  28806. * @param forEach defines a predicate used to filter results
  28807. * @returns an array of Light
  28808. */
  28809. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28810. return this._getByTags(this.lights, tagsQuery, forEach);
  28811. };
  28812. /**
  28813. * Get a list of materials by tags
  28814. * @param tagsQuery defines the tags query to use
  28815. * @param forEach defines a predicate used to filter results
  28816. * @returns an array of Material
  28817. */
  28818. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28819. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28820. };
  28821. /**
  28822. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28823. * This allowed control for front to back rendering or reversly depending of the special needs.
  28824. *
  28825. * @param renderingGroupId The rendering group id corresponding to its index
  28826. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28827. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28828. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28829. */
  28830. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28831. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28832. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28833. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28834. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28835. };
  28836. /**
  28837. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28838. *
  28839. * @param renderingGroupId The rendering group id corresponding to its index
  28840. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28841. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28842. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28843. */
  28844. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28845. if (depth === void 0) { depth = true; }
  28846. if (stencil === void 0) { stencil = true; }
  28847. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28848. };
  28849. /**
  28850. * Will flag all materials as dirty to trigger new shader compilation
  28851. * @param flag defines the flag used to specify which material part must be marked as dirty
  28852. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28853. */
  28854. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28855. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28856. var material = _a[_i];
  28857. if (predicate && !predicate(material)) {
  28858. continue;
  28859. }
  28860. material.markAsDirty(flag);
  28861. }
  28862. };
  28863. /** @hidden */
  28864. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28865. var _this = this;
  28866. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28867. this._activeRequests.push(request);
  28868. request.onCompleteObservable.add(function (request) {
  28869. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28870. });
  28871. return request;
  28872. };
  28873. /** @hidden */
  28874. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28875. var _this = this;
  28876. return new Promise(function (resolve, reject) {
  28877. _this._loadFile(url, function (data) {
  28878. resolve(data);
  28879. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28880. reject(exception);
  28881. });
  28882. });
  28883. };
  28884. // Statics
  28885. Scene._FOGMODE_NONE = 0;
  28886. Scene._FOGMODE_EXP = 1;
  28887. Scene._FOGMODE_EXP2 = 2;
  28888. Scene._FOGMODE_LINEAR = 3;
  28889. Scene._uniqueIdCounter = 0;
  28890. /**
  28891. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28892. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28893. */
  28894. Scene.MinDeltaTime = 1.0;
  28895. /**
  28896. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28897. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28898. */
  28899. Scene.MaxDeltaTime = 1000.0;
  28900. /** The distance in pixel that you have to move to prevent some events */
  28901. Scene.DragMovementThreshold = 10; // in pixels
  28902. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28903. Scene.LongPressDelay = 500; // in milliseconds
  28904. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28905. Scene.DoubleClickDelay = 300; // in milliseconds
  28906. /** If you need to check double click without raising a single click at first click, enable this flag */
  28907. Scene.ExclusiveDoubleClickMode = false;
  28908. return Scene;
  28909. }());
  28910. BABYLON.Scene = Scene;
  28911. })(BABYLON || (BABYLON = {}));
  28912. //# sourceMappingURL=babylon.scene.js.map
  28913. var BABYLON;
  28914. (function (BABYLON) {
  28915. /**
  28916. * Set of assets to keep when moving a scene into an asset container.
  28917. */
  28918. var KeepAssets = /** @class */ (function () {
  28919. function KeepAssets() {
  28920. /**
  28921. * Cameras to keep.
  28922. */
  28923. this.cameras = new Array();
  28924. /**
  28925. * Lights to keep.
  28926. */
  28927. this.lights = new Array();
  28928. /**
  28929. * Meshes to keep.
  28930. */
  28931. this.meshes = new Array();
  28932. /**
  28933. * Skeletons to keep.
  28934. */
  28935. this.skeletons = new Array();
  28936. /**
  28937. * ParticleSystems to keep.
  28938. */
  28939. this.particleSystems = new Array();
  28940. /**
  28941. * Animations to keep.
  28942. */
  28943. this.animations = new Array();
  28944. /**
  28945. * AnimationGroups to keep.
  28946. */
  28947. this.animationGroups = new Array();
  28948. /**
  28949. * MultiMaterials to keep.
  28950. */
  28951. this.multiMaterials = new Array();
  28952. /**
  28953. * Materials to keep.
  28954. */
  28955. this.materials = new Array();
  28956. /**
  28957. * MorphTargetManagers to keep.
  28958. */
  28959. this.morphTargetManagers = new Array();
  28960. /**
  28961. * Geometries to keep.
  28962. */
  28963. this.geometries = new Array();
  28964. /**
  28965. * TransformNodes to keep.
  28966. */
  28967. this.transformNodes = new Array();
  28968. /**
  28969. * LensFlareSystems to keep.
  28970. */
  28971. this.lensFlareSystems = new Array();
  28972. /**
  28973. * ShadowGenerators to keep.
  28974. */
  28975. this.shadowGenerators = new Array();
  28976. /**
  28977. * ActionManagers to keep.
  28978. */
  28979. this.actionManagers = new Array();
  28980. /**
  28981. * Sounds to keep.
  28982. */
  28983. this.sounds = new Array();
  28984. /**
  28985. * Textures to keep.
  28986. */
  28987. this.textures = new Array();
  28988. /**
  28989. * Effect layers to keep.
  28990. */
  28991. this.effectLayers = new Array();
  28992. }
  28993. return KeepAssets;
  28994. }());
  28995. BABYLON.KeepAssets = KeepAssets;
  28996. /**
  28997. * Container with a set of assets that can be added or removed from a scene.
  28998. */
  28999. var AssetContainer = /** @class */ (function () {
  29000. /**
  29001. * Instantiates an AssetContainer.
  29002. * @param scene The scene the AssetContainer belongs to.
  29003. */
  29004. function AssetContainer(scene) {
  29005. // Objects
  29006. /**
  29007. * Cameras populated in the container.
  29008. */
  29009. this.cameras = new Array();
  29010. /**
  29011. * Lights populated in the container.
  29012. */
  29013. this.lights = new Array();
  29014. /**
  29015. * Meshes populated in the container.
  29016. */
  29017. this.meshes = new Array();
  29018. /**
  29019. * Skeletons populated in the container.
  29020. */
  29021. this.skeletons = new Array();
  29022. /**
  29023. * ParticleSystems populated in the container.
  29024. */
  29025. this.particleSystems = new Array();
  29026. /**
  29027. * Animations populated in the container.
  29028. */
  29029. this.animations = new Array();
  29030. /**
  29031. * AnimationGroups populated in the container.
  29032. */
  29033. this.animationGroups = new Array();
  29034. /**
  29035. * MultiMaterials populated in the container.
  29036. */
  29037. this.multiMaterials = new Array();
  29038. /**
  29039. * Materials populated in the container.
  29040. */
  29041. this.materials = new Array();
  29042. /**
  29043. * MorphTargetManagers populated in the container.
  29044. */
  29045. this.morphTargetManagers = new Array();
  29046. /**
  29047. * Geometries populated in the container.
  29048. */
  29049. this.geometries = new Array();
  29050. /**
  29051. * TransformNodes populated in the container.
  29052. */
  29053. this.transformNodes = new Array();
  29054. /**
  29055. * LensFlareSystems populated in the container.
  29056. */
  29057. this.lensFlareSystems = new Array();
  29058. /**
  29059. * ShadowGenerators populated in the container.
  29060. */
  29061. this.shadowGenerators = new Array();
  29062. /**
  29063. * ActionManagers populated in the container.
  29064. */
  29065. this.actionManagers = new Array();
  29066. /**
  29067. * Sounds populated in the container.
  29068. */
  29069. this.sounds = new Array();
  29070. /**
  29071. * Textures populated in the container.
  29072. */
  29073. this.textures = new Array();
  29074. /**
  29075. * Effect layers populated in the container.
  29076. */
  29077. this.effectLayers = new Array();
  29078. this.scene = scene;
  29079. }
  29080. /**
  29081. * Adds all the assets from the container to the scene.
  29082. */
  29083. AssetContainer.prototype.addAllToScene = function () {
  29084. var _this = this;
  29085. this.cameras.forEach(function (o) {
  29086. _this.scene.addCamera(o);
  29087. });
  29088. this.lights.forEach(function (o) {
  29089. _this.scene.addLight(o);
  29090. });
  29091. this.meshes.forEach(function (o) {
  29092. _this.scene.addMesh(o);
  29093. });
  29094. this.skeletons.forEach(function (o) {
  29095. _this.scene.addSkeleton(o);
  29096. });
  29097. this.particleSystems.forEach(function (o) {
  29098. _this.scene.addParticleSystem(o);
  29099. });
  29100. this.animations.forEach(function (o) {
  29101. _this.scene.addAnimation(o);
  29102. });
  29103. this.animationGroups.forEach(function (o) {
  29104. _this.scene.addAnimationGroup(o);
  29105. });
  29106. this.multiMaterials.forEach(function (o) {
  29107. _this.scene.addMultiMaterial(o);
  29108. });
  29109. this.materials.forEach(function (o) {
  29110. _this.scene.addMaterial(o);
  29111. });
  29112. this.morphTargetManagers.forEach(function (o) {
  29113. _this.scene.addMorphTargetManager(o);
  29114. });
  29115. this.geometries.forEach(function (o) {
  29116. _this.scene.addGeometry(o);
  29117. });
  29118. this.transformNodes.forEach(function (o) {
  29119. _this.scene.addTransformNode(o);
  29120. });
  29121. this.lensFlareSystems.forEach(function (o) {
  29122. _this.scene.addLensFlareSystem(o);
  29123. });
  29124. this.actionManagers.forEach(function (o) {
  29125. _this.scene.addActionManager(o);
  29126. });
  29127. this.sounds.forEach(function (o) {
  29128. o.play();
  29129. o.autoplay = true;
  29130. _this.scene.mainSoundTrack.AddSound(o);
  29131. });
  29132. this.textures.forEach(function (o) {
  29133. _this.scene.addTexture(o);
  29134. });
  29135. this.effectLayers.forEach(function (o) {
  29136. _this.scene.addEffectLayer(o);
  29137. });
  29138. };
  29139. /**
  29140. * Removes all the assets in the container from the scene
  29141. */
  29142. AssetContainer.prototype.removeAllFromScene = function () {
  29143. var _this = this;
  29144. this.cameras.forEach(function (o) {
  29145. _this.scene.removeCamera(o);
  29146. });
  29147. this.lights.forEach(function (o) {
  29148. _this.scene.removeLight(o);
  29149. });
  29150. this.meshes.forEach(function (o) {
  29151. _this.scene.removeMesh(o);
  29152. });
  29153. this.skeletons.forEach(function (o) {
  29154. _this.scene.removeSkeleton(o);
  29155. });
  29156. this.particleSystems.forEach(function (o) {
  29157. _this.scene.removeParticleSystem(o);
  29158. });
  29159. this.animations.forEach(function (o) {
  29160. _this.scene.removeAnimation(o);
  29161. });
  29162. this.animationGroups.forEach(function (o) {
  29163. _this.scene.removeAnimationGroup(o);
  29164. });
  29165. this.multiMaterials.forEach(function (o) {
  29166. _this.scene.removeMultiMaterial(o);
  29167. });
  29168. this.materials.forEach(function (o) {
  29169. _this.scene.removeMaterial(o);
  29170. });
  29171. this.morphTargetManagers.forEach(function (o) {
  29172. _this.scene.removeMorphTargetManager(o);
  29173. });
  29174. this.geometries.forEach(function (o) {
  29175. _this.scene.removeGeometry(o);
  29176. });
  29177. this.transformNodes.forEach(function (o) {
  29178. _this.scene.removeTransformNode(o);
  29179. });
  29180. this.lensFlareSystems.forEach(function (o) {
  29181. _this.scene.removeLensFlareSystem(o);
  29182. });
  29183. this.actionManagers.forEach(function (o) {
  29184. _this.scene.removeActionManager(o);
  29185. });
  29186. this.sounds.forEach(function (o) {
  29187. o.stop();
  29188. o.autoplay = false;
  29189. _this.scene.mainSoundTrack.RemoveSound(o);
  29190. });
  29191. this.textures.forEach(function (o) {
  29192. _this.scene.removeTexture(o);
  29193. });
  29194. this.effectLayers.forEach(function (o) {
  29195. _this.scene.removeEffectLayer(o);
  29196. });
  29197. };
  29198. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29199. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29200. var asset = sourceAssets_1[_i];
  29201. var move = true;
  29202. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29203. var keepAsset = keepAssets_1[_a];
  29204. if (asset === keepAsset) {
  29205. move = false;
  29206. break;
  29207. }
  29208. }
  29209. if (move) {
  29210. targetAssets.push(asset);
  29211. }
  29212. }
  29213. };
  29214. /**
  29215. * Removes all the assets contained in the scene and adds them to the container.
  29216. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29217. */
  29218. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29219. if (keepAssets === undefined) {
  29220. keepAssets = new KeepAssets();
  29221. }
  29222. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29223. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29224. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29225. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29226. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29227. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29228. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29229. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29230. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29231. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29232. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29233. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29234. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29235. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29236. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29237. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29238. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29239. this.removeAllFromScene();
  29240. };
  29241. return AssetContainer;
  29242. }());
  29243. BABYLON.AssetContainer = AssetContainer;
  29244. })(BABYLON || (BABYLON = {}));
  29245. //# sourceMappingURL=babylon.assetContainer.js.map
  29246. var BABYLON;
  29247. (function (BABYLON) {
  29248. var Buffer = /** @class */ (function () {
  29249. /**
  29250. * Constructor
  29251. * @param engine the engine
  29252. * @param data the data to use for this buffer
  29253. * @param updatable whether the data is updatable
  29254. * @param stride the stride (optional)
  29255. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29256. * @param instanced whether the buffer is instanced (optional)
  29257. * @param useBytes set to true if the stride in in bytes (optional)
  29258. */
  29259. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29260. if (stride === void 0) { stride = 0; }
  29261. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29262. if (instanced === void 0) { instanced = false; }
  29263. if (useBytes === void 0) { useBytes = false; }
  29264. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29265. this._engine = engine.getScene().getEngine();
  29266. }
  29267. else {
  29268. this._engine = engine;
  29269. }
  29270. this._updatable = updatable;
  29271. this._instanced = instanced;
  29272. this._data = data;
  29273. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29274. if (!postponeInternalCreation) { // by default
  29275. this.create();
  29276. }
  29277. }
  29278. /**
  29279. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29280. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29281. * @param offset defines offset in the buffer (0 by default)
  29282. * @param size defines the size in floats of attributes (position is 3 for instance)
  29283. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29284. * @param instanced defines if the vertex buffer contains indexed data
  29285. * @param useBytes defines if the offset and stride are in bytes
  29286. * @returns the new vertex buffer
  29287. */
  29288. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29289. if (useBytes === void 0) { useBytes = false; }
  29290. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29291. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29292. // a lot of these parameters are ignored as they are overriden by the buffer
  29293. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29294. };
  29295. // Properties
  29296. Buffer.prototype.isUpdatable = function () {
  29297. return this._updatable;
  29298. };
  29299. Buffer.prototype.getData = function () {
  29300. return this._data;
  29301. };
  29302. Buffer.prototype.getBuffer = function () {
  29303. return this._buffer;
  29304. };
  29305. /**
  29306. * Gets the stride in float32 units (i.e. byte stride / 4).
  29307. * May not be an integer if the byte stride is not divisible by 4.
  29308. * DEPRECATED. Use byteStride instead.
  29309. * @returns the stride in float32 units
  29310. */
  29311. Buffer.prototype.getStrideSize = function () {
  29312. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29313. };
  29314. // Methods
  29315. Buffer.prototype.create = function (data) {
  29316. if (data === void 0) { data = null; }
  29317. if (!data && this._buffer) {
  29318. return; // nothing to do
  29319. }
  29320. data = data || this._data;
  29321. if (!data) {
  29322. return;
  29323. }
  29324. if (!this._buffer) { // create buffer
  29325. if (this._updatable) {
  29326. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29327. this._data = data;
  29328. }
  29329. else {
  29330. this._buffer = this._engine.createVertexBuffer(data);
  29331. }
  29332. }
  29333. else if (this._updatable) { // update buffer
  29334. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29335. this._data = data;
  29336. }
  29337. };
  29338. Buffer.prototype._rebuild = function () {
  29339. this._buffer = null;
  29340. this.create(this._data);
  29341. };
  29342. Buffer.prototype.update = function (data) {
  29343. this.create(data);
  29344. };
  29345. /**
  29346. * Updates the data directly.
  29347. * @param data the new data
  29348. * @param offset the new offset
  29349. * @param vertexCount the vertex count (optional)
  29350. * @param useBytes set to true if the offset is in bytes
  29351. */
  29352. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29353. if (useBytes === void 0) { useBytes = false; }
  29354. if (!this._buffer) {
  29355. return;
  29356. }
  29357. if (this._updatable) { // update buffer
  29358. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29359. this._data = null;
  29360. }
  29361. };
  29362. Buffer.prototype.dispose = function () {
  29363. if (!this._buffer) {
  29364. return;
  29365. }
  29366. if (this._engine._releaseBuffer(this._buffer)) {
  29367. this._buffer = null;
  29368. }
  29369. };
  29370. return Buffer;
  29371. }());
  29372. BABYLON.Buffer = Buffer;
  29373. })(BABYLON || (BABYLON = {}));
  29374. //# sourceMappingURL=babylon.buffer.js.map
  29375. var BABYLON;
  29376. (function (BABYLON) {
  29377. var VertexBuffer = /** @class */ (function () {
  29378. /**
  29379. * Constructor
  29380. * @param engine the engine
  29381. * @param data the data to use for this vertex buffer
  29382. * @param kind the vertex buffer kind
  29383. * @param updatable whether the data is updatable
  29384. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29385. * @param stride the stride (optional)
  29386. * @param instanced whether the buffer is instanced (optional)
  29387. * @param offset the offset of the data (optional)
  29388. * @param size the number of components (optional)
  29389. * @param type the type of the component (optional)
  29390. * @param normalized whether the data contains normalized data (optional)
  29391. * @param useBytes set to true if stride and offset are in bytes (optional)
  29392. */
  29393. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29394. if (normalized === void 0) { normalized = false; }
  29395. if (useBytes === void 0) { useBytes = false; }
  29396. if (data instanceof BABYLON.Buffer) {
  29397. this._buffer = data;
  29398. this._ownsBuffer = false;
  29399. }
  29400. else {
  29401. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29402. this._ownsBuffer = true;
  29403. }
  29404. this._kind = kind;
  29405. if (type == undefined) {
  29406. var data_1 = this.getData();
  29407. this.type = VertexBuffer.FLOAT;
  29408. if (data_1 instanceof Int8Array)
  29409. this.type = VertexBuffer.BYTE;
  29410. else if (data_1 instanceof Uint8Array)
  29411. this.type = VertexBuffer.UNSIGNED_BYTE;
  29412. else if (data_1 instanceof Int16Array)
  29413. this.type = VertexBuffer.SHORT;
  29414. else if (data_1 instanceof Uint16Array)
  29415. this.type = VertexBuffer.UNSIGNED_SHORT;
  29416. else if (data_1 instanceof Int32Array)
  29417. this.type = VertexBuffer.INT;
  29418. else if (data_1 instanceof Uint32Array)
  29419. this.type = VertexBuffer.UNSIGNED_INT;
  29420. }
  29421. else {
  29422. this.type = type;
  29423. }
  29424. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29425. if (useBytes) {
  29426. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29427. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29428. this.byteOffset = offset || 0;
  29429. }
  29430. else {
  29431. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29432. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29433. this.byteOffset = (offset || 0) * typeByteLength;
  29434. }
  29435. this.normalized = normalized;
  29436. this._instanced = instanced !== undefined ? instanced : false;
  29437. this._instanceDivisor = instanced ? 1 : 0;
  29438. }
  29439. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29440. /**
  29441. * Gets or sets the instance divisor when in instanced mode
  29442. */
  29443. get: function () {
  29444. return this._instanceDivisor;
  29445. },
  29446. set: function (value) {
  29447. this._instanceDivisor = value;
  29448. if (value == 0) {
  29449. this._instanced = false;
  29450. }
  29451. else {
  29452. this._instanced = true;
  29453. }
  29454. },
  29455. enumerable: true,
  29456. configurable: true
  29457. });
  29458. VertexBuffer.prototype._rebuild = function () {
  29459. if (!this._buffer) {
  29460. return;
  29461. }
  29462. this._buffer._rebuild();
  29463. };
  29464. /**
  29465. * Returns the kind of the VertexBuffer (string).
  29466. */
  29467. VertexBuffer.prototype.getKind = function () {
  29468. return this._kind;
  29469. };
  29470. // Properties
  29471. /**
  29472. * Boolean : is the VertexBuffer updatable ?
  29473. */
  29474. VertexBuffer.prototype.isUpdatable = function () {
  29475. return this._buffer.isUpdatable();
  29476. };
  29477. /**
  29478. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29479. */
  29480. VertexBuffer.prototype.getData = function () {
  29481. return this._buffer.getData();
  29482. };
  29483. /**
  29484. * Returns the WebGLBuffer associated to the VertexBuffer.
  29485. */
  29486. VertexBuffer.prototype.getBuffer = function () {
  29487. return this._buffer.getBuffer();
  29488. };
  29489. /**
  29490. * Returns the stride as a multiple of the type byte length.
  29491. * DEPRECATED. Use byteStride instead.
  29492. */
  29493. VertexBuffer.prototype.getStrideSize = function () {
  29494. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29495. };
  29496. /**
  29497. * Returns the offset as a multiple of the type byte length.
  29498. * DEPRECATED. Use byteOffset instead.
  29499. */
  29500. VertexBuffer.prototype.getOffset = function () {
  29501. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29502. };
  29503. /**
  29504. * Returns the number of components per vertex attribute (integer).
  29505. */
  29506. VertexBuffer.prototype.getSize = function () {
  29507. return this._size;
  29508. };
  29509. /**
  29510. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29511. */
  29512. VertexBuffer.prototype.getIsInstanced = function () {
  29513. return this._instanced;
  29514. };
  29515. /**
  29516. * Returns the instancing divisor, zero for non-instanced (integer).
  29517. */
  29518. VertexBuffer.prototype.getInstanceDivisor = function () {
  29519. return this._instanceDivisor;
  29520. };
  29521. // Methods
  29522. /**
  29523. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29524. * Returns the created WebGLBuffer.
  29525. */
  29526. VertexBuffer.prototype.create = function (data) {
  29527. return this._buffer.create(data);
  29528. };
  29529. /**
  29530. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29531. * This function will create a new buffer if the current one is not updatable
  29532. * Returns the updated WebGLBuffer.
  29533. */
  29534. VertexBuffer.prototype.update = function (data) {
  29535. return this._buffer.update(data);
  29536. };
  29537. /**
  29538. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29539. * Returns the directly updated WebGLBuffer.
  29540. * @param data the new data
  29541. * @param offset the new offset
  29542. * @param useBytes set to true if the offset is in bytes
  29543. */
  29544. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29545. if (useBytes === void 0) { useBytes = false; }
  29546. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29547. };
  29548. /**
  29549. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29550. */
  29551. VertexBuffer.prototype.dispose = function () {
  29552. if (this._ownsBuffer) {
  29553. this._buffer.dispose();
  29554. }
  29555. };
  29556. /**
  29557. * Enumerates each value of this vertex buffer as numbers.
  29558. * @param count the number of values to enumerate
  29559. * @param callback the callback function called for each value
  29560. */
  29561. VertexBuffer.prototype.forEach = function (count, callback) {
  29562. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29563. };
  29564. Object.defineProperty(VertexBuffer, "PositionKind", {
  29565. get: function () {
  29566. return VertexBuffer._PositionKind;
  29567. },
  29568. enumerable: true,
  29569. configurable: true
  29570. });
  29571. Object.defineProperty(VertexBuffer, "NormalKind", {
  29572. get: function () {
  29573. return VertexBuffer._NormalKind;
  29574. },
  29575. enumerable: true,
  29576. configurable: true
  29577. });
  29578. Object.defineProperty(VertexBuffer, "TangentKind", {
  29579. get: function () {
  29580. return VertexBuffer._TangentKind;
  29581. },
  29582. enumerable: true,
  29583. configurable: true
  29584. });
  29585. Object.defineProperty(VertexBuffer, "UVKind", {
  29586. get: function () {
  29587. return VertexBuffer._UVKind;
  29588. },
  29589. enumerable: true,
  29590. configurable: true
  29591. });
  29592. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29593. get: function () {
  29594. return VertexBuffer._UV2Kind;
  29595. },
  29596. enumerable: true,
  29597. configurable: true
  29598. });
  29599. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29600. get: function () {
  29601. return VertexBuffer._UV3Kind;
  29602. },
  29603. enumerable: true,
  29604. configurable: true
  29605. });
  29606. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29607. get: function () {
  29608. return VertexBuffer._UV4Kind;
  29609. },
  29610. enumerable: true,
  29611. configurable: true
  29612. });
  29613. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29614. get: function () {
  29615. return VertexBuffer._UV5Kind;
  29616. },
  29617. enumerable: true,
  29618. configurable: true
  29619. });
  29620. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29621. get: function () {
  29622. return VertexBuffer._UV6Kind;
  29623. },
  29624. enumerable: true,
  29625. configurable: true
  29626. });
  29627. Object.defineProperty(VertexBuffer, "ColorKind", {
  29628. get: function () {
  29629. return VertexBuffer._ColorKind;
  29630. },
  29631. enumerable: true,
  29632. configurable: true
  29633. });
  29634. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29635. get: function () {
  29636. return VertexBuffer._MatricesIndicesKind;
  29637. },
  29638. enumerable: true,
  29639. configurable: true
  29640. });
  29641. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29642. get: function () {
  29643. return VertexBuffer._MatricesWeightsKind;
  29644. },
  29645. enumerable: true,
  29646. configurable: true
  29647. });
  29648. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29649. get: function () {
  29650. return VertexBuffer._MatricesIndicesExtraKind;
  29651. },
  29652. enumerable: true,
  29653. configurable: true
  29654. });
  29655. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29656. get: function () {
  29657. return VertexBuffer._MatricesWeightsExtraKind;
  29658. },
  29659. enumerable: true,
  29660. configurable: true
  29661. });
  29662. /**
  29663. * Deduces the stride given a kind.
  29664. * @param kind The kind string to deduce
  29665. * @returns The deduced stride
  29666. */
  29667. VertexBuffer.DeduceStride = function (kind) {
  29668. switch (kind) {
  29669. case VertexBuffer.UVKind:
  29670. case VertexBuffer.UV2Kind:
  29671. case VertexBuffer.UV3Kind:
  29672. case VertexBuffer.UV4Kind:
  29673. case VertexBuffer.UV5Kind:
  29674. case VertexBuffer.UV6Kind:
  29675. return 2;
  29676. case VertexBuffer.NormalKind:
  29677. case VertexBuffer.PositionKind:
  29678. return 3;
  29679. case VertexBuffer.ColorKind:
  29680. case VertexBuffer.MatricesIndicesKind:
  29681. case VertexBuffer.MatricesIndicesExtraKind:
  29682. case VertexBuffer.MatricesWeightsKind:
  29683. case VertexBuffer.MatricesWeightsExtraKind:
  29684. case VertexBuffer.TangentKind:
  29685. return 4;
  29686. default:
  29687. throw new Error("Invalid kind '" + kind + "'");
  29688. }
  29689. };
  29690. /**
  29691. * Gets the byte length of the given type.
  29692. * @param type the type
  29693. * @returns the number of bytes
  29694. */
  29695. VertexBuffer.GetTypeByteLength = function (type) {
  29696. switch (type) {
  29697. case VertexBuffer.BYTE:
  29698. case VertexBuffer.UNSIGNED_BYTE:
  29699. return 1;
  29700. case VertexBuffer.SHORT:
  29701. case VertexBuffer.UNSIGNED_SHORT:
  29702. return 2;
  29703. case VertexBuffer.INT:
  29704. case VertexBuffer.FLOAT:
  29705. return 4;
  29706. default:
  29707. throw new Error("Invalid type '" + type + "'");
  29708. }
  29709. };
  29710. /**
  29711. * Enumerates each value of the given parameters as numbers.
  29712. * @param data the data to enumerate
  29713. * @param byteOffset the byte offset of the data
  29714. * @param byteStride the byte stride of the data
  29715. * @param componentCount the number of components per element
  29716. * @param componentType the type of the component
  29717. * @param count the total number of components
  29718. * @param normalized whether the data is normalized
  29719. * @param callback the callback function called for each value
  29720. */
  29721. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29722. if (data instanceof Array) {
  29723. var offset = byteOffset / 4;
  29724. var stride = byteStride / 4;
  29725. for (var index = 0; index < count; index += componentCount) {
  29726. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29727. callback(data[offset + componentIndex], index + componentIndex);
  29728. }
  29729. offset += stride;
  29730. }
  29731. }
  29732. else {
  29733. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29734. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29735. for (var index = 0; index < count; index += componentCount) {
  29736. var componentByteOffset = byteOffset;
  29737. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29738. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29739. callback(value, index + componentIndex);
  29740. componentByteOffset += componentByteLength;
  29741. }
  29742. byteOffset += byteStride;
  29743. }
  29744. }
  29745. };
  29746. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29747. switch (type) {
  29748. case VertexBuffer.BYTE: {
  29749. var value = dataView.getInt8(byteOffset);
  29750. if (normalized) {
  29751. value = Math.max(value / 127, -1);
  29752. }
  29753. return value;
  29754. }
  29755. case VertexBuffer.UNSIGNED_BYTE: {
  29756. var value = dataView.getUint8(byteOffset);
  29757. if (normalized) {
  29758. value = value / 255;
  29759. }
  29760. return value;
  29761. }
  29762. case VertexBuffer.SHORT: {
  29763. var value = dataView.getInt16(byteOffset, true);
  29764. if (normalized) {
  29765. value = Math.max(value / 16383, -1);
  29766. }
  29767. return value;
  29768. }
  29769. case VertexBuffer.UNSIGNED_SHORT: {
  29770. var value = dataView.getUint16(byteOffset, true);
  29771. if (normalized) {
  29772. value = value / 65535;
  29773. }
  29774. return value;
  29775. }
  29776. case VertexBuffer.FLOAT: {
  29777. return dataView.getFloat32(byteOffset, true);
  29778. }
  29779. default: {
  29780. throw new Error("Invalid component type " + type);
  29781. }
  29782. }
  29783. };
  29784. /**
  29785. * The byte type.
  29786. */
  29787. VertexBuffer.BYTE = 5120;
  29788. /**
  29789. * The unsigned byte type.
  29790. */
  29791. VertexBuffer.UNSIGNED_BYTE = 5121;
  29792. /**
  29793. * The short type.
  29794. */
  29795. VertexBuffer.SHORT = 5122;
  29796. /**
  29797. * The unsigned short type.
  29798. */
  29799. VertexBuffer.UNSIGNED_SHORT = 5123;
  29800. /**
  29801. * The integer type.
  29802. */
  29803. VertexBuffer.INT = 5124;
  29804. /**
  29805. * The unsigned integer type.
  29806. */
  29807. VertexBuffer.UNSIGNED_INT = 5125;
  29808. /**
  29809. * The float type.
  29810. */
  29811. VertexBuffer.FLOAT = 5126;
  29812. // Enums
  29813. VertexBuffer._PositionKind = "position";
  29814. VertexBuffer._NormalKind = "normal";
  29815. VertexBuffer._TangentKind = "tangent";
  29816. VertexBuffer._UVKind = "uv";
  29817. VertexBuffer._UV2Kind = "uv2";
  29818. VertexBuffer._UV3Kind = "uv3";
  29819. VertexBuffer._UV4Kind = "uv4";
  29820. VertexBuffer._UV5Kind = "uv5";
  29821. VertexBuffer._UV6Kind = "uv6";
  29822. VertexBuffer._ColorKind = "color";
  29823. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29824. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29825. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29826. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29827. return VertexBuffer;
  29828. }());
  29829. BABYLON.VertexBuffer = VertexBuffer;
  29830. })(BABYLON || (BABYLON = {}));
  29831. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29832. var BABYLON;
  29833. (function (BABYLON) {
  29834. /**
  29835. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29836. */
  29837. var DummyInternalTextureTracker = /** @class */ (function () {
  29838. function DummyInternalTextureTracker() {
  29839. /**
  29840. * Gets or set the previous tracker in the list
  29841. */
  29842. this.previous = null;
  29843. /**
  29844. * Gets or set the next tracker in the list
  29845. */
  29846. this.next = null;
  29847. }
  29848. return DummyInternalTextureTracker;
  29849. }());
  29850. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29851. })(BABYLON || (BABYLON = {}));
  29852. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29853. var BABYLON;
  29854. (function (BABYLON) {
  29855. /**
  29856. * Class used to store data associated with WebGL texture data for the engine
  29857. * This class should not be used directly
  29858. */
  29859. var InternalTexture = /** @class */ (function () {
  29860. /**
  29861. * Creates a new InternalTexture
  29862. * @param engine defines the engine to use
  29863. * @param dataSource defines the type of data that will be used
  29864. */
  29865. function InternalTexture(engine, dataSource) {
  29866. /**
  29867. * Observable called when the texture is loaded
  29868. */
  29869. this.onLoadedObservable = new BABYLON.Observable();
  29870. /**
  29871. * Gets or set the previous tracker in the list
  29872. */
  29873. this.previous = null;
  29874. /**
  29875. * Gets or set the next tracker in the list
  29876. */
  29877. this.next = null;
  29878. // Private
  29879. /** @hidden */
  29880. this._initialSlot = -1;
  29881. /** @hidden */
  29882. this._designatedSlot = -1;
  29883. /** @hidden */
  29884. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29885. /** @hidden */
  29886. this._comparisonFunction = 0;
  29887. /** @hidden */
  29888. this._references = 1;
  29889. this._engine = engine;
  29890. this._dataSource = dataSource;
  29891. this._webGLTexture = engine._createTexture();
  29892. }
  29893. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29894. /**
  29895. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29896. */
  29897. get: function () {
  29898. return this._dataSource;
  29899. },
  29900. enumerable: true,
  29901. configurable: true
  29902. });
  29903. /**
  29904. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29905. */
  29906. InternalTexture.prototype.incrementReferences = function () {
  29907. this._references++;
  29908. };
  29909. /**
  29910. * Change the size of the texture (not the size of the content)
  29911. * @param width defines the new width
  29912. * @param height defines the new height
  29913. * @param depth defines the new depth (1 by default)
  29914. */
  29915. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29916. if (depth === void 0) { depth = 1; }
  29917. this.width = width;
  29918. this.height = height;
  29919. this.depth = depth;
  29920. this.baseWidth = width;
  29921. this.baseHeight = height;
  29922. this.baseDepth = depth;
  29923. this._size = width * height * depth;
  29924. };
  29925. /** @hidden */
  29926. InternalTexture.prototype._rebuild = function () {
  29927. var _this = this;
  29928. var proxy;
  29929. this.isReady = false;
  29930. this._cachedCoordinatesMode = null;
  29931. this._cachedWrapU = null;
  29932. this._cachedWrapV = null;
  29933. this._cachedAnisotropicFilteringLevel = null;
  29934. switch (this._dataSource) {
  29935. case InternalTexture.DATASOURCE_TEMP:
  29936. return;
  29937. case InternalTexture.DATASOURCE_URL:
  29938. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29939. _this.isReady = true;
  29940. }, null, this._buffer, undefined, this.format);
  29941. proxy._swapAndDie(this);
  29942. return;
  29943. case InternalTexture.DATASOURCE_RAW:
  29944. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29945. proxy._swapAndDie(this);
  29946. this.isReady = true;
  29947. return;
  29948. case InternalTexture.DATASOURCE_RAW3D:
  29949. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29950. proxy._swapAndDie(this);
  29951. this.isReady = true;
  29952. return;
  29953. case InternalTexture.DATASOURCE_DYNAMIC:
  29954. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29955. proxy._swapAndDie(this);
  29956. // The engine will make sure to update content so no need to flag it as isReady = true
  29957. return;
  29958. case InternalTexture.DATASOURCE_RENDERTARGET:
  29959. var options = new BABYLON.RenderTargetCreationOptions();
  29960. options.generateDepthBuffer = this._generateDepthBuffer;
  29961. options.generateMipMaps = this.generateMipMaps;
  29962. options.generateStencilBuffer = this._generateStencilBuffer;
  29963. options.samplingMode = this.samplingMode;
  29964. options.type = this.type;
  29965. if (this.isCube) {
  29966. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29967. }
  29968. else {
  29969. var size = {
  29970. width: this.width,
  29971. height: this.height
  29972. };
  29973. proxy = this._engine.createRenderTargetTexture(size, options);
  29974. }
  29975. proxy._swapAndDie(this);
  29976. this.isReady = true;
  29977. return;
  29978. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29979. var depthTextureOptions = {
  29980. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29981. comparisonFunction: this._comparisonFunction,
  29982. generateStencil: this._generateStencilBuffer,
  29983. isCube: this.isCube
  29984. };
  29985. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29986. proxy._swapAndDie(this);
  29987. this.isReady = true;
  29988. return;
  29989. case InternalTexture.DATASOURCE_CUBE:
  29990. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29991. _this.isReady = true;
  29992. }, null, this.format, this._extension);
  29993. proxy._swapAndDie(this);
  29994. return;
  29995. case InternalTexture.DATASOURCE_CUBERAW:
  29996. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29997. proxy._swapAndDie(this);
  29998. this.isReady = true;
  29999. return;
  30000. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30001. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30002. if (proxy) {
  30003. proxy._swapAndDie(_this);
  30004. }
  30005. _this.isReady = true;
  30006. }, null, this.format, this._extension);
  30007. return;
  30008. }
  30009. };
  30010. InternalTexture.prototype._swapAndDie = function (target) {
  30011. target._webGLTexture = this._webGLTexture;
  30012. if (this._framebuffer) {
  30013. target._framebuffer = this._framebuffer;
  30014. }
  30015. if (this._depthStencilBuffer) {
  30016. target._depthStencilBuffer = this._depthStencilBuffer;
  30017. }
  30018. if (this._lodTextureHigh) {
  30019. if (target._lodTextureHigh) {
  30020. target._lodTextureHigh.dispose();
  30021. }
  30022. target._lodTextureHigh = this._lodTextureHigh;
  30023. }
  30024. if (this._lodTextureMid) {
  30025. if (target._lodTextureMid) {
  30026. target._lodTextureMid.dispose();
  30027. }
  30028. target._lodTextureMid = this._lodTextureMid;
  30029. }
  30030. if (this._lodTextureLow) {
  30031. if (target._lodTextureLow) {
  30032. target._lodTextureLow.dispose();
  30033. }
  30034. target._lodTextureLow = this._lodTextureLow;
  30035. }
  30036. var cache = this._engine.getLoadedTexturesCache();
  30037. var index = cache.indexOf(this);
  30038. if (index !== -1) {
  30039. cache.splice(index, 1);
  30040. }
  30041. };
  30042. /**
  30043. * Dispose the current allocated resources
  30044. */
  30045. InternalTexture.prototype.dispose = function () {
  30046. if (!this._webGLTexture) {
  30047. return;
  30048. }
  30049. this._references--;
  30050. if (this._references === 0) {
  30051. this._engine._releaseTexture(this);
  30052. this._webGLTexture = null;
  30053. this.previous = null;
  30054. this.next = null;
  30055. }
  30056. };
  30057. /**
  30058. * The source of the texture data is unknown
  30059. */
  30060. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30061. /**
  30062. * Texture data comes from an URL
  30063. */
  30064. InternalTexture.DATASOURCE_URL = 1;
  30065. /**
  30066. * Texture data is only used for temporary storage
  30067. */
  30068. InternalTexture.DATASOURCE_TEMP = 2;
  30069. /**
  30070. * Texture data comes from raw data (ArrayBuffer)
  30071. */
  30072. InternalTexture.DATASOURCE_RAW = 3;
  30073. /**
  30074. * Texture content is dynamic (video or dynamic texture)
  30075. */
  30076. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30077. /**
  30078. * Texture content is generated by rendering to it
  30079. */
  30080. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30081. /**
  30082. * Texture content is part of a multi render target process
  30083. */
  30084. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30085. /**
  30086. * Texture data comes from a cube data file
  30087. */
  30088. InternalTexture.DATASOURCE_CUBE = 7;
  30089. /**
  30090. * Texture data comes from a raw cube data
  30091. */
  30092. InternalTexture.DATASOURCE_CUBERAW = 8;
  30093. /**
  30094. * Texture data come from a prefiltered cube data file
  30095. */
  30096. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30097. /**
  30098. * Texture content is raw 3D data
  30099. */
  30100. InternalTexture.DATASOURCE_RAW3D = 10;
  30101. /**
  30102. * Texture content is a depth texture
  30103. */
  30104. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30105. return InternalTexture;
  30106. }());
  30107. BABYLON.InternalTexture = InternalTexture;
  30108. })(BABYLON || (BABYLON = {}));
  30109. //# sourceMappingURL=babylon.internalTexture.js.map
  30110. var BABYLON;
  30111. (function (BABYLON) {
  30112. var BaseTexture = /** @class */ (function () {
  30113. function BaseTexture(scene) {
  30114. this._hasAlpha = false;
  30115. this.getAlphaFromRGB = false;
  30116. this.level = 1;
  30117. this.coordinatesIndex = 0;
  30118. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30119. /**
  30120. * | Value | Type | Description |
  30121. * | ----- | ------------------ | ----------- |
  30122. * | 0 | CLAMP_ADDRESSMODE | |
  30123. * | 1 | WRAP_ADDRESSMODE | |
  30124. * | 2 | MIRROR_ADDRESSMODE | |
  30125. */
  30126. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30127. /**
  30128. * | Value | Type | Description |
  30129. * | ----- | ------------------ | ----------- |
  30130. * | 0 | CLAMP_ADDRESSMODE | |
  30131. * | 1 | WRAP_ADDRESSMODE | |
  30132. * | 2 | MIRROR_ADDRESSMODE | |
  30133. */
  30134. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30135. /**
  30136. * | Value | Type | Description |
  30137. * | ----- | ------------------ | ----------- |
  30138. * | 0 | CLAMP_ADDRESSMODE | |
  30139. * | 1 | WRAP_ADDRESSMODE | |
  30140. * | 2 | MIRROR_ADDRESSMODE | |
  30141. */
  30142. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30143. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30144. this.isCube = false;
  30145. this.is3D = false;
  30146. this.gammaSpace = true;
  30147. this.invertZ = false;
  30148. this.lodLevelInAlpha = false;
  30149. this.lodGenerationOffset = 0.0;
  30150. this.lodGenerationScale = 0.8;
  30151. this.isRenderTarget = false;
  30152. this.animations = new Array();
  30153. /**
  30154. * An event triggered when the texture is disposed.
  30155. */
  30156. this.onDisposeObservable = new BABYLON.Observable();
  30157. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30158. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30159. if (this._scene) {
  30160. this._scene.textures.push(this);
  30161. }
  30162. this._uid = null;
  30163. }
  30164. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30165. get: function () {
  30166. return this._hasAlpha;
  30167. },
  30168. set: function (value) {
  30169. if (this._hasAlpha === value) {
  30170. return;
  30171. }
  30172. this._hasAlpha = value;
  30173. if (this._scene) {
  30174. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30175. }
  30176. },
  30177. enumerable: true,
  30178. configurable: true
  30179. });
  30180. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30181. get: function () {
  30182. return this._coordinatesMode;
  30183. },
  30184. /**
  30185. * How a texture is mapped.
  30186. *
  30187. * | Value | Type | Description |
  30188. * | ----- | ----------------------------------- | ----------- |
  30189. * | 0 | EXPLICIT_MODE | |
  30190. * | 1 | SPHERICAL_MODE | |
  30191. * | 2 | PLANAR_MODE | |
  30192. * | 3 | CUBIC_MODE | |
  30193. * | 4 | PROJECTION_MODE | |
  30194. * | 5 | SKYBOX_MODE | |
  30195. * | 6 | INVCUBIC_MODE | |
  30196. * | 7 | EQUIRECTANGULAR_MODE | |
  30197. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30198. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30199. */
  30200. set: function (value) {
  30201. if (this._coordinatesMode === value) {
  30202. return;
  30203. }
  30204. this._coordinatesMode = value;
  30205. if (this._scene) {
  30206. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30207. }
  30208. },
  30209. enumerable: true,
  30210. configurable: true
  30211. });
  30212. Object.defineProperty(BaseTexture.prototype, "uid", {
  30213. get: function () {
  30214. if (!this._uid) {
  30215. this._uid = BABYLON.Tools.RandomId();
  30216. }
  30217. return this._uid;
  30218. },
  30219. enumerable: true,
  30220. configurable: true
  30221. });
  30222. BaseTexture.prototype.toString = function () {
  30223. return this.name;
  30224. };
  30225. BaseTexture.prototype.getClassName = function () {
  30226. return "BaseTexture";
  30227. };
  30228. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30229. set: function (callback) {
  30230. if (this._onDisposeObserver) {
  30231. this.onDisposeObservable.remove(this._onDisposeObserver);
  30232. }
  30233. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30234. },
  30235. enumerable: true,
  30236. configurable: true
  30237. });
  30238. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30239. get: function () {
  30240. return true;
  30241. },
  30242. enumerable: true,
  30243. configurable: true
  30244. });
  30245. BaseTexture.prototype.getScene = function () {
  30246. return this._scene;
  30247. };
  30248. BaseTexture.prototype.getTextureMatrix = function () {
  30249. return BABYLON.Matrix.IdentityReadOnly;
  30250. };
  30251. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30252. return BABYLON.Matrix.IdentityReadOnly;
  30253. };
  30254. BaseTexture.prototype.getInternalTexture = function () {
  30255. return this._texture;
  30256. };
  30257. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30258. return !this.isBlocking || this.isReady();
  30259. };
  30260. BaseTexture.prototype.isReady = function () {
  30261. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30262. this.delayLoad();
  30263. return false;
  30264. }
  30265. if (this._texture) {
  30266. return this._texture.isReady;
  30267. }
  30268. return false;
  30269. };
  30270. BaseTexture.prototype.getSize = function () {
  30271. if (this._texture && this._texture.width) {
  30272. return new BABYLON.Size(this._texture.width, this._texture.height);
  30273. }
  30274. if (this._texture && this._texture._size) {
  30275. return new BABYLON.Size(this._texture._size, this._texture._size);
  30276. }
  30277. return BABYLON.Size.Zero();
  30278. };
  30279. BaseTexture.prototype.getBaseSize = function () {
  30280. if (!this.isReady() || !this._texture)
  30281. return BABYLON.Size.Zero();
  30282. if (this._texture._size) {
  30283. return new BABYLON.Size(this._texture._size, this._texture._size);
  30284. }
  30285. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30286. };
  30287. BaseTexture.prototype.scale = function (ratio) {
  30288. };
  30289. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30290. get: function () {
  30291. return false;
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30297. if (!this._scene) {
  30298. return null;
  30299. }
  30300. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30301. for (var index = 0; index < texturesCache.length; index++) {
  30302. var texturesCacheEntry = texturesCache[index];
  30303. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30304. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30305. texturesCacheEntry.incrementReferences();
  30306. return texturesCacheEntry;
  30307. }
  30308. }
  30309. }
  30310. return null;
  30311. };
  30312. BaseTexture.prototype._rebuild = function () {
  30313. };
  30314. BaseTexture.prototype.delayLoad = function () {
  30315. };
  30316. BaseTexture.prototype.clone = function () {
  30317. return null;
  30318. };
  30319. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30320. get: function () {
  30321. if (!this._texture) {
  30322. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30323. }
  30324. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30330. get: function () {
  30331. if (!this._texture) {
  30332. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30333. }
  30334. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. BaseTexture.prototype.readPixels = function (faceIndex) {
  30340. if (faceIndex === void 0) { faceIndex = 0; }
  30341. if (!this._texture) {
  30342. return null;
  30343. }
  30344. var size = this.getSize();
  30345. var scene = this.getScene();
  30346. if (!scene) {
  30347. return null;
  30348. }
  30349. var engine = scene.getEngine();
  30350. if (this._texture.isCube) {
  30351. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30352. }
  30353. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30354. };
  30355. BaseTexture.prototype.releaseInternalTexture = function () {
  30356. if (this._texture) {
  30357. this._texture.dispose();
  30358. this._texture = null;
  30359. }
  30360. };
  30361. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30362. get: function () {
  30363. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30364. return null;
  30365. }
  30366. if (!this._texture._sphericalPolynomial) {
  30367. this._texture._sphericalPolynomial =
  30368. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30369. }
  30370. return this._texture._sphericalPolynomial;
  30371. },
  30372. set: function (value) {
  30373. if (this._texture) {
  30374. this._texture._sphericalPolynomial = value;
  30375. }
  30376. },
  30377. enumerable: true,
  30378. configurable: true
  30379. });
  30380. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30381. get: function () {
  30382. if (this._texture) {
  30383. return this._texture._lodTextureHigh;
  30384. }
  30385. return null;
  30386. },
  30387. enumerable: true,
  30388. configurable: true
  30389. });
  30390. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30391. get: function () {
  30392. if (this._texture) {
  30393. return this._texture._lodTextureMid;
  30394. }
  30395. return null;
  30396. },
  30397. enumerable: true,
  30398. configurable: true
  30399. });
  30400. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30401. get: function () {
  30402. if (this._texture) {
  30403. return this._texture._lodTextureLow;
  30404. }
  30405. return null;
  30406. },
  30407. enumerable: true,
  30408. configurable: true
  30409. });
  30410. BaseTexture.prototype.dispose = function () {
  30411. if (!this._scene) {
  30412. return;
  30413. }
  30414. // Animations
  30415. this._scene.stopAnimation(this);
  30416. // Remove from scene
  30417. this._scene._removePendingData(this);
  30418. var index = this._scene.textures.indexOf(this);
  30419. if (index >= 0) {
  30420. this._scene.textures.splice(index, 1);
  30421. }
  30422. if (this._texture === undefined) {
  30423. return;
  30424. }
  30425. // Release
  30426. this.releaseInternalTexture();
  30427. // Callback
  30428. this.onDisposeObservable.notifyObservers(this);
  30429. this.onDisposeObservable.clear();
  30430. };
  30431. BaseTexture.prototype.serialize = function () {
  30432. if (!this.name) {
  30433. return null;
  30434. }
  30435. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30436. // Animations
  30437. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30438. return serializationObject;
  30439. };
  30440. BaseTexture.WhenAllReady = function (textures, callback) {
  30441. var numRemaining = textures.length;
  30442. if (numRemaining === 0) {
  30443. callback();
  30444. return;
  30445. }
  30446. var _loop_1 = function () {
  30447. texture = textures[i];
  30448. if (texture.isReady()) {
  30449. if (--numRemaining === 0) {
  30450. callback();
  30451. }
  30452. }
  30453. else {
  30454. onLoadObservable = texture.onLoadObservable;
  30455. var onLoadCallback_1 = function () {
  30456. onLoadObservable.removeCallback(onLoadCallback_1);
  30457. if (--numRemaining === 0) {
  30458. callback();
  30459. }
  30460. };
  30461. onLoadObservable.add(onLoadCallback_1);
  30462. }
  30463. };
  30464. var texture, onLoadObservable;
  30465. for (var i = 0; i < textures.length; i++) {
  30466. _loop_1();
  30467. }
  30468. };
  30469. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30470. __decorate([
  30471. BABYLON.serialize()
  30472. ], BaseTexture.prototype, "name", void 0);
  30473. __decorate([
  30474. BABYLON.serialize("hasAlpha")
  30475. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30476. __decorate([
  30477. BABYLON.serialize()
  30478. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30479. __decorate([
  30480. BABYLON.serialize()
  30481. ], BaseTexture.prototype, "level", void 0);
  30482. __decorate([
  30483. BABYLON.serialize()
  30484. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30485. __decorate([
  30486. BABYLON.serialize("coordinatesMode")
  30487. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30488. __decorate([
  30489. BABYLON.serialize()
  30490. ], BaseTexture.prototype, "wrapU", void 0);
  30491. __decorate([
  30492. BABYLON.serialize()
  30493. ], BaseTexture.prototype, "wrapV", void 0);
  30494. __decorate([
  30495. BABYLON.serialize()
  30496. ], BaseTexture.prototype, "wrapR", void 0);
  30497. __decorate([
  30498. BABYLON.serialize()
  30499. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30500. __decorate([
  30501. BABYLON.serialize()
  30502. ], BaseTexture.prototype, "isCube", void 0);
  30503. __decorate([
  30504. BABYLON.serialize()
  30505. ], BaseTexture.prototype, "is3D", void 0);
  30506. __decorate([
  30507. BABYLON.serialize()
  30508. ], BaseTexture.prototype, "gammaSpace", void 0);
  30509. __decorate([
  30510. BABYLON.serialize()
  30511. ], BaseTexture.prototype, "invertZ", void 0);
  30512. __decorate([
  30513. BABYLON.serialize()
  30514. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30515. __decorate([
  30516. BABYLON.serialize()
  30517. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30518. __decorate([
  30519. BABYLON.serialize()
  30520. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30521. __decorate([
  30522. BABYLON.serialize()
  30523. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30524. return BaseTexture;
  30525. }());
  30526. BABYLON.BaseTexture = BaseTexture;
  30527. })(BABYLON || (BABYLON = {}));
  30528. //# sourceMappingURL=babylon.baseTexture.js.map
  30529. var BABYLON;
  30530. (function (BABYLON) {
  30531. var Texture = /** @class */ (function (_super) {
  30532. __extends(Texture, _super);
  30533. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30534. if (noMipmap === void 0) { noMipmap = false; }
  30535. if (invertY === void 0) { invertY = true; }
  30536. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30537. if (onLoad === void 0) { onLoad = null; }
  30538. if (onError === void 0) { onError = null; }
  30539. if (buffer === void 0) { buffer = null; }
  30540. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30541. var _this = _super.call(this, scene) || this;
  30542. _this.uOffset = 0;
  30543. _this.vOffset = 0;
  30544. _this.uScale = 1.0;
  30545. _this.vScale = 1.0;
  30546. _this.uAng = 0;
  30547. _this.vAng = 0;
  30548. _this.wAng = 0;
  30549. /**
  30550. * Defines the center of rotation (U)
  30551. */
  30552. _this.uRotationCenter = 0.5;
  30553. /**
  30554. * Defines the center of rotation (V)
  30555. */
  30556. _this.vRotationCenter = 0.5;
  30557. /**
  30558. * Defines the center of rotation (W)
  30559. */
  30560. _this.wRotationCenter = 0.5;
  30561. _this._isBlocking = true;
  30562. _this.name = url || "";
  30563. _this.url = url;
  30564. _this._noMipmap = noMipmap;
  30565. _this._invertY = invertY;
  30566. _this._samplingMode = samplingMode;
  30567. _this._buffer = buffer;
  30568. _this._deleteBuffer = deleteBuffer;
  30569. if (format) {
  30570. _this._format = format;
  30571. }
  30572. scene = _this.getScene();
  30573. if (!scene) {
  30574. return _this;
  30575. }
  30576. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30577. var load = function () {
  30578. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30579. _this.onLoadObservable.notifyObservers(_this);
  30580. }
  30581. if (onLoad) {
  30582. onLoad();
  30583. }
  30584. if (!_this.isBlocking && scene) {
  30585. scene.resetCachedMaterial();
  30586. }
  30587. };
  30588. if (!_this.url) {
  30589. _this._delayedOnLoad = load;
  30590. _this._delayedOnError = onError;
  30591. return _this;
  30592. }
  30593. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30594. if (!_this._texture) {
  30595. if (!scene.useDelayedTextureLoading) {
  30596. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30597. if (deleteBuffer) {
  30598. delete _this._buffer;
  30599. }
  30600. }
  30601. else {
  30602. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30603. _this._delayedOnLoad = load;
  30604. _this._delayedOnError = onError;
  30605. }
  30606. }
  30607. else {
  30608. if (_this._texture.isReady) {
  30609. BABYLON.Tools.SetImmediate(function () { return load(); });
  30610. }
  30611. else {
  30612. _this._texture.onLoadedObservable.add(load);
  30613. }
  30614. }
  30615. return _this;
  30616. }
  30617. Object.defineProperty(Texture.prototype, "noMipmap", {
  30618. get: function () {
  30619. return this._noMipmap;
  30620. },
  30621. enumerable: true,
  30622. configurable: true
  30623. });
  30624. Object.defineProperty(Texture.prototype, "isBlocking", {
  30625. get: function () {
  30626. return this._isBlocking;
  30627. },
  30628. set: function (value) {
  30629. this._isBlocking = value;
  30630. },
  30631. enumerable: true,
  30632. configurable: true
  30633. });
  30634. Object.defineProperty(Texture.prototype, "samplingMode", {
  30635. get: function () {
  30636. return this._samplingMode;
  30637. },
  30638. enumerable: true,
  30639. configurable: true
  30640. });
  30641. /**
  30642. * Update the url (and optional buffer) of this texture if url was null during construction.
  30643. * @param url the url of the texture
  30644. * @param buffer the buffer of the texture (defaults to null)
  30645. */
  30646. Texture.prototype.updateURL = function (url, buffer) {
  30647. if (buffer === void 0) { buffer = null; }
  30648. if (this.url) {
  30649. throw new Error("URL is already set");
  30650. }
  30651. this.url = url;
  30652. this._buffer = buffer;
  30653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30654. this.delayLoad();
  30655. };
  30656. Texture.prototype.delayLoad = function () {
  30657. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30658. return;
  30659. }
  30660. var scene = this.getScene();
  30661. if (!scene) {
  30662. return;
  30663. }
  30664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30665. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30666. if (!this._texture) {
  30667. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30668. if (this._deleteBuffer) {
  30669. delete this._buffer;
  30670. }
  30671. }
  30672. else {
  30673. if (this._delayedOnLoad) {
  30674. if (this._texture.isReady) {
  30675. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30676. }
  30677. else {
  30678. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30679. }
  30680. }
  30681. }
  30682. this._delayedOnLoad = null;
  30683. this._delayedOnError = null;
  30684. };
  30685. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30686. if (!this._texture) {
  30687. return;
  30688. }
  30689. var scene = this.getScene();
  30690. if (!scene) {
  30691. return;
  30692. }
  30693. this._samplingMode = samplingMode;
  30694. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30695. };
  30696. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30697. x *= this.uScale;
  30698. y *= this.vScale;
  30699. x -= this.uRotationCenter * this.uScale;
  30700. y -= this.vRotationCenter * this.vScale;
  30701. z -= this.wRotationCenter;
  30702. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30703. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30704. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30705. t.z += this.wRotationCenter;
  30706. };
  30707. Texture.prototype.getTextureMatrix = function () {
  30708. var _this = this;
  30709. if (this.uOffset === this._cachedUOffset &&
  30710. this.vOffset === this._cachedVOffset &&
  30711. this.uScale === this._cachedUScale &&
  30712. this.vScale === this._cachedVScale &&
  30713. this.uAng === this._cachedUAng &&
  30714. this.vAng === this._cachedVAng &&
  30715. this.wAng === this._cachedWAng) {
  30716. return this._cachedTextureMatrix;
  30717. }
  30718. this._cachedUOffset = this.uOffset;
  30719. this._cachedVOffset = this.vOffset;
  30720. this._cachedUScale = this.uScale;
  30721. this._cachedVScale = this.vScale;
  30722. this._cachedUAng = this.uAng;
  30723. this._cachedVAng = this.vAng;
  30724. this._cachedWAng = this.wAng;
  30725. if (!this._cachedTextureMatrix) {
  30726. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30727. this._rowGenerationMatrix = new BABYLON.Matrix();
  30728. this._t0 = BABYLON.Vector3.Zero();
  30729. this._t1 = BABYLON.Vector3.Zero();
  30730. this._t2 = BABYLON.Vector3.Zero();
  30731. }
  30732. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30733. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30734. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30735. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30736. this._t1.subtractInPlace(this._t0);
  30737. this._t2.subtractInPlace(this._t0);
  30738. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30739. this._cachedTextureMatrix.m[0] = this._t1.x;
  30740. this._cachedTextureMatrix.m[1] = this._t1.y;
  30741. this._cachedTextureMatrix.m[2] = this._t1.z;
  30742. this._cachedTextureMatrix.m[4] = this._t2.x;
  30743. this._cachedTextureMatrix.m[5] = this._t2.y;
  30744. this._cachedTextureMatrix.m[6] = this._t2.z;
  30745. this._cachedTextureMatrix.m[8] = this._t0.x;
  30746. this._cachedTextureMatrix.m[9] = this._t0.y;
  30747. this._cachedTextureMatrix.m[10] = this._t0.z;
  30748. var scene = this.getScene();
  30749. if (!scene) {
  30750. return this._cachedTextureMatrix;
  30751. }
  30752. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30753. return mat.hasTexture(_this);
  30754. });
  30755. return this._cachedTextureMatrix;
  30756. };
  30757. Texture.prototype.getReflectionTextureMatrix = function () {
  30758. var _this = this;
  30759. var scene = this.getScene();
  30760. if (!scene) {
  30761. return this._cachedTextureMatrix;
  30762. }
  30763. if (this.uOffset === this._cachedUOffset &&
  30764. this.vOffset === this._cachedVOffset &&
  30765. this.uScale === this._cachedUScale &&
  30766. this.vScale === this._cachedVScale &&
  30767. this.coordinatesMode === this._cachedCoordinatesMode) {
  30768. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30769. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30770. return this._cachedTextureMatrix;
  30771. }
  30772. }
  30773. else {
  30774. return this._cachedTextureMatrix;
  30775. }
  30776. }
  30777. if (!this._cachedTextureMatrix) {
  30778. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30779. }
  30780. if (!this._projectionModeMatrix) {
  30781. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30782. }
  30783. this._cachedUOffset = this.uOffset;
  30784. this._cachedVOffset = this.vOffset;
  30785. this._cachedUScale = this.uScale;
  30786. this._cachedVScale = this.vScale;
  30787. this._cachedCoordinatesMode = this.coordinatesMode;
  30788. switch (this.coordinatesMode) {
  30789. case Texture.PLANAR_MODE:
  30790. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30791. this._cachedTextureMatrix[0] = this.uScale;
  30792. this._cachedTextureMatrix[5] = this.vScale;
  30793. this._cachedTextureMatrix[12] = this.uOffset;
  30794. this._cachedTextureMatrix[13] = this.vOffset;
  30795. break;
  30796. case Texture.PROJECTION_MODE:
  30797. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30798. this._projectionModeMatrix.m[0] = 0.5;
  30799. this._projectionModeMatrix.m[5] = -0.5;
  30800. this._projectionModeMatrix.m[10] = 0.0;
  30801. this._projectionModeMatrix.m[12] = 0.5;
  30802. this._projectionModeMatrix.m[13] = 0.5;
  30803. this._projectionModeMatrix.m[14] = 1.0;
  30804. this._projectionModeMatrix.m[15] = 1.0;
  30805. var projectionMatrix = scene.getProjectionMatrix();
  30806. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30807. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30808. break;
  30809. default:
  30810. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30811. break;
  30812. }
  30813. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30814. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30815. });
  30816. return this._cachedTextureMatrix;
  30817. };
  30818. Texture.prototype.clone = function () {
  30819. var _this = this;
  30820. return BABYLON.SerializationHelper.Clone(function () {
  30821. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30822. }, this);
  30823. };
  30824. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30825. get: function () {
  30826. if (!this._onLoadObservable) {
  30827. this._onLoadObservable = new BABYLON.Observable();
  30828. }
  30829. return this._onLoadObservable;
  30830. },
  30831. enumerable: true,
  30832. configurable: true
  30833. });
  30834. Texture.prototype.serialize = function () {
  30835. var serializationObject = _super.prototype.serialize.call(this);
  30836. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30837. serializationObject.base64String = this._buffer;
  30838. serializationObject.name = serializationObject.name.replace("data:", "");
  30839. }
  30840. serializationObject.invertY = this._invertY;
  30841. serializationObject.samplingMode = this.samplingMode;
  30842. return serializationObject;
  30843. };
  30844. Texture.prototype.getClassName = function () {
  30845. return "Texture";
  30846. };
  30847. Texture.prototype.dispose = function () {
  30848. _super.prototype.dispose.call(this);
  30849. if (this.onLoadObservable) {
  30850. this.onLoadObservable.clear();
  30851. this._onLoadObservable = null;
  30852. }
  30853. this._delayedOnLoad = null;
  30854. this._delayedOnError = null;
  30855. };
  30856. // Statics
  30857. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30858. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30859. if (onLoad === void 0) { onLoad = null; }
  30860. if (onError === void 0) { onError = null; }
  30861. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30862. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30863. };
  30864. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30865. if (parsedTexture.customType) {
  30866. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30867. // Update Sampling Mode
  30868. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30869. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30870. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30871. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30872. }
  30873. }
  30874. return parsedCustomTexture;
  30875. }
  30876. if (parsedTexture.isCube) {
  30877. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30878. }
  30879. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30880. return null;
  30881. }
  30882. var texture = BABYLON.SerializationHelper.Parse(function () {
  30883. var generateMipMaps = true;
  30884. if (parsedTexture.noMipmap) {
  30885. generateMipMaps = false;
  30886. }
  30887. if (parsedTexture.mirrorPlane) {
  30888. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30889. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30890. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30891. return mirrorTexture;
  30892. }
  30893. else if (parsedTexture.isRenderTarget) {
  30894. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30895. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30896. return renderTargetTexture;
  30897. }
  30898. else {
  30899. var texture;
  30900. if (parsedTexture.base64String) {
  30901. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30902. }
  30903. else {
  30904. var url = rootUrl + parsedTexture.name;
  30905. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30906. url = parsedTexture.url;
  30907. }
  30908. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30909. }
  30910. return texture;
  30911. }
  30912. }, parsedTexture, scene);
  30913. // Update Sampling Mode
  30914. if (parsedTexture.samplingMode) {
  30915. var sampling = parsedTexture.samplingMode;
  30916. if (texture._samplingMode !== sampling) {
  30917. texture.updateSamplingMode(sampling);
  30918. }
  30919. }
  30920. // Animations
  30921. if (parsedTexture.animations) {
  30922. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30923. var parsedAnimation = parsedTexture.animations[animationIndex];
  30924. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30925. }
  30926. }
  30927. return texture;
  30928. };
  30929. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30930. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30931. if (noMipmap === void 0) { noMipmap = false; }
  30932. if (invertY === void 0) { invertY = true; }
  30933. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30934. if (onLoad === void 0) { onLoad = null; }
  30935. if (onError === void 0) { onError = null; }
  30936. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30937. if (name.substr(0, 5) !== "data:") {
  30938. name = "data:" + name;
  30939. }
  30940. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30941. };
  30942. // Constants
  30943. Texture.NEAREST_SAMPLINGMODE = 1;
  30944. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30945. Texture.BILINEAR_SAMPLINGMODE = 2;
  30946. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30947. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30948. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30949. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30950. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30951. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30952. Texture.NEAREST_LINEAR = 7;
  30953. Texture.NEAREST_NEAREST = 8;
  30954. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30955. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30956. Texture.LINEAR_LINEAR = 11;
  30957. Texture.LINEAR_NEAREST = 12;
  30958. Texture.EXPLICIT_MODE = 0;
  30959. Texture.SPHERICAL_MODE = 1;
  30960. Texture.PLANAR_MODE = 2;
  30961. Texture.CUBIC_MODE = 3;
  30962. Texture.PROJECTION_MODE = 4;
  30963. Texture.SKYBOX_MODE = 5;
  30964. Texture.INVCUBIC_MODE = 6;
  30965. Texture.EQUIRECTANGULAR_MODE = 7;
  30966. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30967. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30968. Texture.CLAMP_ADDRESSMODE = 0;
  30969. Texture.WRAP_ADDRESSMODE = 1;
  30970. Texture.MIRROR_ADDRESSMODE = 2;
  30971. /**
  30972. * 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
  30973. */
  30974. Texture.UseSerializedUrlIfAny = false;
  30975. __decorate([
  30976. BABYLON.serialize()
  30977. ], Texture.prototype, "url", void 0);
  30978. __decorate([
  30979. BABYLON.serialize()
  30980. ], Texture.prototype, "uOffset", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], Texture.prototype, "vOffset", void 0);
  30984. __decorate([
  30985. BABYLON.serialize()
  30986. ], Texture.prototype, "uScale", void 0);
  30987. __decorate([
  30988. BABYLON.serialize()
  30989. ], Texture.prototype, "vScale", void 0);
  30990. __decorate([
  30991. BABYLON.serialize()
  30992. ], Texture.prototype, "uAng", void 0);
  30993. __decorate([
  30994. BABYLON.serialize()
  30995. ], Texture.prototype, "vAng", void 0);
  30996. __decorate([
  30997. BABYLON.serialize()
  30998. ], Texture.prototype, "wAng", void 0);
  30999. __decorate([
  31000. BABYLON.serialize()
  31001. ], Texture.prototype, "uRotationCenter", void 0);
  31002. __decorate([
  31003. BABYLON.serialize()
  31004. ], Texture.prototype, "vRotationCenter", void 0);
  31005. __decorate([
  31006. BABYLON.serialize()
  31007. ], Texture.prototype, "wRotationCenter", void 0);
  31008. __decorate([
  31009. BABYLON.serialize()
  31010. ], Texture.prototype, "isBlocking", null);
  31011. return Texture;
  31012. }(BABYLON.BaseTexture));
  31013. BABYLON.Texture = Texture;
  31014. })(BABYLON || (BABYLON = {}));
  31015. //# sourceMappingURL=babylon.texture.js.map
  31016. var BABYLON;
  31017. (function (BABYLON) {
  31018. /**
  31019. * @hidden
  31020. **/
  31021. var _InstancesBatch = /** @class */ (function () {
  31022. function _InstancesBatch() {
  31023. this.mustReturn = false;
  31024. this.visibleInstances = new Array();
  31025. this.renderSelf = new Array();
  31026. }
  31027. return _InstancesBatch;
  31028. }());
  31029. BABYLON._InstancesBatch = _InstancesBatch;
  31030. var Mesh = /** @class */ (function (_super) {
  31031. __extends(Mesh, _super);
  31032. /**
  31033. * @constructor
  31034. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31035. * @param {Scene} scene The scene to add this mesh to.
  31036. * @param {Node} parent The parent of this mesh, if it has one
  31037. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31038. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31039. * When false, achieved by calling a clone(), also passing False.
  31040. * This will make creation of children, recursive.
  31041. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31042. */
  31043. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31044. if (scene === void 0) { scene = null; }
  31045. if (parent === void 0) { parent = null; }
  31046. if (source === void 0) { source = null; }
  31047. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31048. var _this = _super.call(this, name, scene) || this;
  31049. // Events
  31050. /**
  31051. * An event triggered before rendering the mesh
  31052. */
  31053. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31054. /**
  31055. * An event triggered after rendering the mesh
  31056. */
  31057. _this.onAfterRenderObservable = new BABYLON.Observable();
  31058. /**
  31059. * An event triggered before drawing the mesh
  31060. */
  31061. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31062. // Members
  31063. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31064. _this.instances = new Array();
  31065. _this._LODLevels = new Array();
  31066. _this._visibleInstances = {};
  31067. _this._renderIdForInstances = new Array();
  31068. _this._batchCache = new _InstancesBatch();
  31069. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31070. // Use by builder only to know what orientation were the mesh build in.
  31071. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31072. _this.overrideMaterialSideOrientation = null;
  31073. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31074. // Will be used to save a source mesh reference, If any
  31075. _this._source = null;
  31076. scene = _this.getScene();
  31077. if (source) {
  31078. // Source mesh
  31079. _this._source = source;
  31080. // Geometry
  31081. if (source._geometry) {
  31082. source._geometry.applyToMesh(_this);
  31083. }
  31084. // Deep copy
  31085. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31086. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  31087. // Metadata
  31088. if (source.metadata && source.metadata.clone) {
  31089. _this.metadata = source.metadata.clone();
  31090. }
  31091. else {
  31092. _this.metadata = source.metadata;
  31093. }
  31094. // Tags
  31095. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31096. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31097. }
  31098. // Parent
  31099. _this.parent = source.parent;
  31100. // Pivot
  31101. _this.setPivotMatrix(source.getPivotMatrix());
  31102. _this.id = name + "." + source.id;
  31103. // Material
  31104. _this.material = source.material;
  31105. var index;
  31106. if (!doNotCloneChildren) {
  31107. // Children
  31108. var directDescendants = source.getDescendants(true);
  31109. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31110. var child = directDescendants[index_1];
  31111. if (child.clone) {
  31112. child.clone(name + "." + child.name, _this);
  31113. }
  31114. }
  31115. }
  31116. // Physics clone
  31117. var physicsEngine = _this.getScene().getPhysicsEngine();
  31118. if (clonePhysicsImpostor && physicsEngine) {
  31119. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31120. if (impostor) {
  31121. _this.physicsImpostor = impostor.clone(_this);
  31122. }
  31123. }
  31124. // Particles
  31125. for (index = 0; index < scene.particleSystems.length; index++) {
  31126. var system = scene.particleSystems[index];
  31127. if (system.emitter === source) {
  31128. system.clone(system.name, _this);
  31129. }
  31130. }
  31131. _this.computeWorldMatrix(true);
  31132. }
  31133. // Parent
  31134. if (parent !== null) {
  31135. _this.parent = parent;
  31136. }
  31137. return _this;
  31138. }
  31139. Object.defineProperty(Mesh, "FRONTSIDE", {
  31140. /**
  31141. * Mesh side orientation : usually the external or front surface
  31142. */
  31143. get: function () {
  31144. return Mesh._FRONTSIDE;
  31145. },
  31146. enumerable: true,
  31147. configurable: true
  31148. });
  31149. Object.defineProperty(Mesh, "BACKSIDE", {
  31150. /**
  31151. * Mesh side orientation : usually the internal or back surface
  31152. */
  31153. get: function () {
  31154. return Mesh._BACKSIDE;
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31160. /**
  31161. * Mesh side orientation : both internal and external or front and back surfaces
  31162. */
  31163. get: function () {
  31164. return Mesh._DOUBLESIDE;
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31170. /**
  31171. * Mesh side orientation : by default, `FRONTSIDE`
  31172. */
  31173. get: function () {
  31174. return Mesh._DEFAULTSIDE;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. Object.defineProperty(Mesh, "NO_CAP", {
  31180. /**
  31181. * Mesh cap setting : no cap
  31182. */
  31183. get: function () {
  31184. return Mesh._NO_CAP;
  31185. },
  31186. enumerable: true,
  31187. configurable: true
  31188. });
  31189. Object.defineProperty(Mesh, "CAP_START", {
  31190. /**
  31191. * Mesh cap setting : one cap at the beginning of the mesh
  31192. */
  31193. get: function () {
  31194. return Mesh._CAP_START;
  31195. },
  31196. enumerable: true,
  31197. configurable: true
  31198. });
  31199. Object.defineProperty(Mesh, "CAP_END", {
  31200. /**
  31201. * Mesh cap setting : one cap at the end of the mesh
  31202. */
  31203. get: function () {
  31204. return Mesh._CAP_END;
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. Object.defineProperty(Mesh, "CAP_ALL", {
  31210. /**
  31211. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31212. */
  31213. get: function () {
  31214. return Mesh._CAP_ALL;
  31215. },
  31216. enumerable: true,
  31217. configurable: true
  31218. });
  31219. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31220. set: function (callback) {
  31221. if (this._onBeforeDrawObserver) {
  31222. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31223. }
  31224. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31225. },
  31226. enumerable: true,
  31227. configurable: true
  31228. });
  31229. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31230. get: function () {
  31231. return this._morphTargetManager;
  31232. },
  31233. set: function (value) {
  31234. if (this._morphTargetManager === value) {
  31235. return;
  31236. }
  31237. this._morphTargetManager = value;
  31238. this._syncGeometryWithMorphTargetManager();
  31239. },
  31240. enumerable: true,
  31241. configurable: true
  31242. });
  31243. Object.defineProperty(Mesh.prototype, "source", {
  31244. get: function () {
  31245. return this._source;
  31246. },
  31247. enumerable: true,
  31248. configurable: true
  31249. });
  31250. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31251. get: function () {
  31252. return this._unIndexed;
  31253. },
  31254. set: function (value) {
  31255. if (this._unIndexed !== value) {
  31256. this._unIndexed = value;
  31257. this._markSubMeshesAsAttributesDirty();
  31258. }
  31259. },
  31260. enumerable: true,
  31261. configurable: true
  31262. });
  31263. // Methods
  31264. /**
  31265. * Returns the string "Mesh".
  31266. */
  31267. Mesh.prototype.getClassName = function () {
  31268. return "Mesh";
  31269. };
  31270. /**
  31271. * Returns a string.
  31272. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31273. */
  31274. Mesh.prototype.toString = function (fullDetails) {
  31275. var ret = _super.prototype.toString.call(this, fullDetails);
  31276. ret += ", n vertices: " + this.getTotalVertices();
  31277. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31278. if (this.animations) {
  31279. for (var i = 0; i < this.animations.length; i++) {
  31280. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31281. }
  31282. }
  31283. if (fullDetails) {
  31284. if (this._geometry) {
  31285. var ib = this.getIndices();
  31286. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31287. if (vb && ib) {
  31288. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31289. }
  31290. }
  31291. else {
  31292. ret += ", flat shading: UNKNOWN";
  31293. }
  31294. }
  31295. return ret;
  31296. };
  31297. Mesh.prototype._unBindEffect = function () {
  31298. _super.prototype._unBindEffect.call(this);
  31299. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31300. var instance = _a[_i];
  31301. instance._unBindEffect();
  31302. }
  31303. };
  31304. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31305. /**
  31306. * True if the mesh has some Levels Of Details (LOD).
  31307. * Returns a boolean.
  31308. */
  31309. get: function () {
  31310. return this._LODLevels.length > 0;
  31311. },
  31312. enumerable: true,
  31313. configurable: true
  31314. });
  31315. /**
  31316. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31317. * @returns an array of {BABYLON.MeshLODLevel}
  31318. */
  31319. Mesh.prototype.getLODLevels = function () {
  31320. return this._LODLevels;
  31321. };
  31322. Mesh.prototype._sortLODLevels = function () {
  31323. this._LODLevels.sort(function (a, b) {
  31324. if (a.distance < b.distance) {
  31325. return 1;
  31326. }
  31327. if (a.distance > b.distance) {
  31328. return -1;
  31329. }
  31330. return 0;
  31331. });
  31332. };
  31333. /**
  31334. * Add a mesh as LOD level triggered at the given distance.
  31335. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31336. * @param {number} distance The distance from the center of the object to show this level
  31337. * @param {Mesh} mesh The mesh to be added as LOD level
  31338. * @return {Mesh} This mesh (for chaining)
  31339. */
  31340. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31341. if (mesh && mesh._masterMesh) {
  31342. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31343. return this;
  31344. }
  31345. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31346. this._LODLevels.push(level);
  31347. if (mesh) {
  31348. mesh._masterMesh = this;
  31349. }
  31350. this._sortLODLevels();
  31351. return this;
  31352. };
  31353. /**
  31354. * Returns the LOD level mesh at the passed distance or null if not found.
  31355. * It is related to the method `addLODLevel(distance, mesh)`.
  31356. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31357. * Returns an object Mesh or `null`.
  31358. */
  31359. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31360. for (var index = 0; index < this._LODLevels.length; index++) {
  31361. var level = this._LODLevels[index];
  31362. if (level.distance === distance) {
  31363. return level.mesh;
  31364. }
  31365. }
  31366. return null;
  31367. };
  31368. /**
  31369. * Remove a mesh from the LOD array
  31370. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31371. * @param {Mesh} mesh The mesh to be removed.
  31372. * @return {Mesh} This mesh (for chaining)
  31373. */
  31374. Mesh.prototype.removeLODLevel = function (mesh) {
  31375. for (var index = 0; index < this._LODLevels.length; index++) {
  31376. if (this._LODLevels[index].mesh === mesh) {
  31377. this._LODLevels.splice(index, 1);
  31378. if (mesh) {
  31379. mesh._masterMesh = null;
  31380. }
  31381. }
  31382. }
  31383. this._sortLODLevels();
  31384. return this;
  31385. };
  31386. /**
  31387. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31388. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31389. */
  31390. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31391. if (!this._LODLevels || this._LODLevels.length === 0) {
  31392. return this;
  31393. }
  31394. var bSphere;
  31395. if (boundingSphere) {
  31396. bSphere = boundingSphere;
  31397. }
  31398. else {
  31399. var boundingInfo = this.getBoundingInfo();
  31400. bSphere = boundingInfo.boundingSphere;
  31401. }
  31402. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31403. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31404. if (this.onLODLevelSelection) {
  31405. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31406. }
  31407. return this;
  31408. }
  31409. for (var index = 0; index < this._LODLevels.length; index++) {
  31410. var level = this._LODLevels[index];
  31411. if (level.distance < distanceToCamera) {
  31412. if (level.mesh) {
  31413. level.mesh._preActivate();
  31414. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31415. }
  31416. if (this.onLODLevelSelection) {
  31417. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31418. }
  31419. return level.mesh;
  31420. }
  31421. }
  31422. if (this.onLODLevelSelection) {
  31423. this.onLODLevelSelection(distanceToCamera, this, this);
  31424. }
  31425. return this;
  31426. };
  31427. Object.defineProperty(Mesh.prototype, "geometry", {
  31428. /**
  31429. * Returns the mesh internal Geometry object.
  31430. */
  31431. get: function () {
  31432. return this._geometry;
  31433. },
  31434. enumerable: true,
  31435. configurable: true
  31436. });
  31437. /**
  31438. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31439. */
  31440. Mesh.prototype.getTotalVertices = function () {
  31441. if (this._geometry === null || this._geometry === undefined) {
  31442. return 0;
  31443. }
  31444. return this._geometry.getTotalVertices();
  31445. };
  31446. /**
  31447. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31448. * 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.
  31449. * You can force the copy with forceCopy === true
  31450. * Returns null if the mesh has no geometry or no vertex buffer.
  31451. * Possible `kind` values :
  31452. * - BABYLON.VertexBuffer.PositionKind
  31453. * - BABYLON.VertexBuffer.UVKind
  31454. * - BABYLON.VertexBuffer.UV2Kind
  31455. * - BABYLON.VertexBuffer.UV3Kind
  31456. * - BABYLON.VertexBuffer.UV4Kind
  31457. * - BABYLON.VertexBuffer.UV5Kind
  31458. * - BABYLON.VertexBuffer.UV6Kind
  31459. * - BABYLON.VertexBuffer.ColorKind
  31460. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31461. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31462. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31463. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31464. */
  31465. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31466. if (!this._geometry) {
  31467. return null;
  31468. }
  31469. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31470. };
  31471. /**
  31472. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31473. * Returns `null` if the mesh has no geometry.
  31474. * Possible `kind` values :
  31475. * - BABYLON.VertexBuffer.PositionKind
  31476. * - BABYLON.VertexBuffer.UVKind
  31477. * - BABYLON.VertexBuffer.UV2Kind
  31478. * - BABYLON.VertexBuffer.UV3Kind
  31479. * - BABYLON.VertexBuffer.UV4Kind
  31480. * - BABYLON.VertexBuffer.UV5Kind
  31481. * - BABYLON.VertexBuffer.UV6Kind
  31482. * - BABYLON.VertexBuffer.ColorKind
  31483. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31484. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31485. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31486. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31487. */
  31488. Mesh.prototype.getVertexBuffer = function (kind) {
  31489. if (!this._geometry) {
  31490. return null;
  31491. }
  31492. return this._geometry.getVertexBuffer(kind);
  31493. };
  31494. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31495. if (!this._geometry) {
  31496. if (this._delayInfo) {
  31497. return this._delayInfo.indexOf(kind) !== -1;
  31498. }
  31499. return false;
  31500. }
  31501. return this._geometry.isVerticesDataPresent(kind);
  31502. };
  31503. /**
  31504. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31505. * Possible `kind` values :
  31506. * - BABYLON.VertexBuffer.PositionKind
  31507. * - BABYLON.VertexBuffer.UVKind
  31508. * - BABYLON.VertexBuffer.UV2Kind
  31509. * - BABYLON.VertexBuffer.UV3Kind
  31510. * - BABYLON.VertexBuffer.UV4Kind
  31511. * - BABYLON.VertexBuffer.UV5Kind
  31512. * - BABYLON.VertexBuffer.UV6Kind
  31513. * - BABYLON.VertexBuffer.ColorKind
  31514. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31515. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31516. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31517. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31518. */
  31519. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31520. if (!this._geometry) {
  31521. if (this._delayInfo) {
  31522. return this._delayInfo.indexOf(kind) !== -1;
  31523. }
  31524. return false;
  31525. }
  31526. return this._geometry.isVertexBufferUpdatable(kind);
  31527. };
  31528. /**
  31529. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31530. * Possible `kind` values :
  31531. * - BABYLON.VertexBuffer.PositionKind
  31532. * - BABYLON.VertexBuffer.UVKind
  31533. * - BABYLON.VertexBuffer.UV2Kind
  31534. * - BABYLON.VertexBuffer.UV3Kind
  31535. * - BABYLON.VertexBuffer.UV4Kind
  31536. * - BABYLON.VertexBuffer.UV5Kind
  31537. * - BABYLON.VertexBuffer.UV6Kind
  31538. * - BABYLON.VertexBuffer.ColorKind
  31539. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31540. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31541. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31542. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31543. */
  31544. Mesh.prototype.getVerticesDataKinds = function () {
  31545. if (!this._geometry) {
  31546. var result = new Array();
  31547. if (this._delayInfo) {
  31548. this._delayInfo.forEach(function (kind, index, array) {
  31549. result.push(kind);
  31550. });
  31551. }
  31552. return result;
  31553. }
  31554. return this._geometry.getVerticesDataKinds();
  31555. };
  31556. /**
  31557. * Returns a positive integer : the total number of indices in this mesh geometry.
  31558. * Returns zero if the mesh has no geometry.
  31559. */
  31560. Mesh.prototype.getTotalIndices = function () {
  31561. if (!this._geometry) {
  31562. return 0;
  31563. }
  31564. return this._geometry.getTotalIndices();
  31565. };
  31566. /**
  31567. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31568. * 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.
  31569. * Returns an empty array if the mesh has no geometry.
  31570. */
  31571. Mesh.prototype.getIndices = function (copyWhenShared) {
  31572. if (!this._geometry) {
  31573. return [];
  31574. }
  31575. return this._geometry.getIndices(copyWhenShared);
  31576. };
  31577. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31578. get: function () {
  31579. return this._masterMesh !== null && this._masterMesh !== undefined;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. /**
  31585. * Determine if the current mesh is ready to be rendered
  31586. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31587. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31588. * @returns true if all associated assets are ready (material, textures, shaders)
  31589. */
  31590. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31591. if (completeCheck === void 0) { completeCheck = false; }
  31592. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31593. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31594. return false;
  31595. }
  31596. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31597. return false;
  31598. }
  31599. if (!this.subMeshes || this.subMeshes.length === 0) {
  31600. return true;
  31601. }
  31602. if (!completeCheck) {
  31603. return true;
  31604. }
  31605. var engine = this.getEngine();
  31606. var scene = this.getScene();
  31607. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31608. this.computeWorldMatrix();
  31609. var mat = this.material || scene.defaultMaterial;
  31610. if (mat) {
  31611. if (mat.storeEffectOnSubMeshes) {
  31612. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31613. var subMesh = _a[_i];
  31614. var effectiveMaterial = subMesh.getMaterial();
  31615. if (effectiveMaterial) {
  31616. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31617. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31618. return false;
  31619. }
  31620. }
  31621. else {
  31622. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31623. return false;
  31624. }
  31625. }
  31626. }
  31627. }
  31628. }
  31629. else {
  31630. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31631. return false;
  31632. }
  31633. }
  31634. }
  31635. // Shadows
  31636. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31637. var light = _c[_b];
  31638. var generator = light.getShadowGenerator();
  31639. if (generator) {
  31640. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31641. var subMesh = _e[_d];
  31642. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31643. return false;
  31644. }
  31645. }
  31646. }
  31647. }
  31648. // LOD
  31649. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31650. var lod = _g[_f];
  31651. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31652. return false;
  31653. }
  31654. }
  31655. return true;
  31656. };
  31657. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31658. /**
  31659. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31660. * This property is pertinent only for updatable parametric shapes.
  31661. */
  31662. get: function () {
  31663. return this._areNormalsFrozen;
  31664. },
  31665. enumerable: true,
  31666. configurable: true
  31667. });
  31668. /**
  31669. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31670. * It has no effect at all on other shapes.
  31671. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31672. * Returns the Mesh.
  31673. */
  31674. Mesh.prototype.freezeNormals = function () {
  31675. this._areNormalsFrozen = true;
  31676. return this;
  31677. };
  31678. /**
  31679. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31680. * It has no effect at all on other shapes.
  31681. * It reactivates the mesh normals computation if it was previously frozen.
  31682. * Returns the Mesh.
  31683. */
  31684. Mesh.prototype.unfreezeNormals = function () {
  31685. this._areNormalsFrozen = false;
  31686. return this;
  31687. };
  31688. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31689. /**
  31690. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31691. */
  31692. set: function (count) {
  31693. this._overridenInstanceCount = count;
  31694. },
  31695. enumerable: true,
  31696. configurable: true
  31697. });
  31698. // Methods
  31699. Mesh.prototype._preActivate = function () {
  31700. var sceneRenderId = this.getScene().getRenderId();
  31701. if (this._preActivateId === sceneRenderId) {
  31702. return this;
  31703. }
  31704. this._preActivateId = sceneRenderId;
  31705. this._visibleInstances = null;
  31706. return this;
  31707. };
  31708. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31709. if (this._visibleInstances) {
  31710. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31711. }
  31712. return this;
  31713. };
  31714. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31715. if (!this._visibleInstances) {
  31716. this._visibleInstances = {};
  31717. this._visibleInstances.defaultRenderId = renderId;
  31718. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31719. }
  31720. if (!this._visibleInstances[renderId]) {
  31721. this._visibleInstances[renderId] = new Array();
  31722. }
  31723. this._visibleInstances[renderId].push(instance);
  31724. return this;
  31725. };
  31726. /**
  31727. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31728. * This means the mesh underlying bounding box and sphere are recomputed.
  31729. * Returns the Mesh.
  31730. */
  31731. Mesh.prototype.refreshBoundingInfo = function () {
  31732. return this._refreshBoundingInfo(false);
  31733. };
  31734. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31735. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31736. return this;
  31737. }
  31738. var data = this._getPositionData(applySkeleton);
  31739. if (data) {
  31740. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31741. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31742. }
  31743. if (this.subMeshes) {
  31744. for (var index = 0; index < this.subMeshes.length; index++) {
  31745. this.subMeshes[index].refreshBoundingInfo();
  31746. }
  31747. }
  31748. this._updateBoundingInfo();
  31749. return this;
  31750. };
  31751. Mesh.prototype._getPositionData = function (applySkeleton) {
  31752. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31753. if (data && applySkeleton && this.skeleton) {
  31754. data = BABYLON.Tools.Slice(data);
  31755. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31756. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31757. if (matricesWeightsData && matricesIndicesData) {
  31758. var needExtras = this.numBoneInfluencers > 4;
  31759. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31760. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31761. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31762. var tempVector = BABYLON.Tmp.Vector3[0];
  31763. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31764. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31765. var matWeightIdx = 0;
  31766. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31767. finalMatrix.reset();
  31768. var inf;
  31769. var weight;
  31770. for (inf = 0; inf < 4; inf++) {
  31771. weight = matricesWeightsData[matWeightIdx + inf];
  31772. if (weight <= 0)
  31773. break;
  31774. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31775. finalMatrix.addToSelf(tempMatrix);
  31776. }
  31777. if (needExtras) {
  31778. for (inf = 0; inf < 4; inf++) {
  31779. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31780. if (weight <= 0)
  31781. break;
  31782. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31783. finalMatrix.addToSelf(tempMatrix);
  31784. }
  31785. }
  31786. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31787. tempVector.toArray(data, index);
  31788. }
  31789. }
  31790. }
  31791. return data;
  31792. };
  31793. Mesh.prototype._createGlobalSubMesh = function (force) {
  31794. var totalVertices = this.getTotalVertices();
  31795. if (!totalVertices || !this.getIndices()) {
  31796. return null;
  31797. }
  31798. // Check if we need to recreate the submeshes
  31799. if (this.subMeshes && this.subMeshes.length > 0) {
  31800. var ib = this.getIndices();
  31801. if (!ib) {
  31802. return null;
  31803. }
  31804. var totalIndices = ib.length;
  31805. var needToRecreate = false;
  31806. if (force) {
  31807. needToRecreate = true;
  31808. }
  31809. else {
  31810. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31811. var submesh = _a[_i];
  31812. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31813. needToRecreate = true;
  31814. break;
  31815. }
  31816. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31817. needToRecreate = true;
  31818. break;
  31819. }
  31820. }
  31821. }
  31822. if (!needToRecreate) {
  31823. return this.subMeshes[0];
  31824. }
  31825. }
  31826. this.releaseSubMeshes();
  31827. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31828. };
  31829. Mesh.prototype.subdivide = function (count) {
  31830. if (count < 1) {
  31831. return;
  31832. }
  31833. var totalIndices = this.getTotalIndices();
  31834. var subdivisionSize = (totalIndices / count) | 0;
  31835. var offset = 0;
  31836. // Ensure that subdivisionSize is a multiple of 3
  31837. while (subdivisionSize % 3 !== 0) {
  31838. subdivisionSize++;
  31839. }
  31840. this.releaseSubMeshes();
  31841. for (var index = 0; index < count; index++) {
  31842. if (offset >= totalIndices) {
  31843. break;
  31844. }
  31845. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31846. offset += subdivisionSize;
  31847. }
  31848. this.synchronizeInstances();
  31849. };
  31850. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31851. if (updatable === void 0) { updatable = false; }
  31852. if (!this._geometry) {
  31853. var vertexData = new BABYLON.VertexData();
  31854. vertexData.set(data, kind);
  31855. var scene = this.getScene();
  31856. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31857. }
  31858. else {
  31859. this._geometry.setVerticesData(kind, data, updatable, stride);
  31860. }
  31861. return this;
  31862. };
  31863. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31864. if (updatable === void 0) { updatable = true; }
  31865. var vb = this.getVertexBuffer(kind);
  31866. if (!vb || vb.isUpdatable() === updatable) {
  31867. return;
  31868. }
  31869. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31870. };
  31871. /**
  31872. * Sets the mesh VertexBuffer.
  31873. * Returns the Mesh.
  31874. */
  31875. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31876. if (!this._geometry) {
  31877. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31878. }
  31879. this._geometry.setVerticesBuffer(buffer);
  31880. return this;
  31881. };
  31882. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31883. if (!this._geometry) {
  31884. return this;
  31885. }
  31886. if (!makeItUnique) {
  31887. this._geometry.updateVerticesData(kind, data, updateExtends);
  31888. }
  31889. else {
  31890. this.makeGeometryUnique();
  31891. this.updateVerticesData(kind, data, updateExtends, false);
  31892. }
  31893. return this;
  31894. };
  31895. /**
  31896. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31897. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31898. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31899. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31900. * Returns the Mesh.
  31901. */
  31902. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31903. if (computeNormals === void 0) { computeNormals = true; }
  31904. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31905. if (!positions) {
  31906. return this;
  31907. }
  31908. positionFunction(positions);
  31909. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31910. if (computeNormals) {
  31911. var indices = this.getIndices();
  31912. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31913. if (!normals) {
  31914. return this;
  31915. }
  31916. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31917. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31918. }
  31919. return this;
  31920. };
  31921. /**
  31922. * Creates a un-shared specific occurence of the geometry for the mesh.
  31923. * Returns the Mesh.
  31924. */
  31925. Mesh.prototype.makeGeometryUnique = function () {
  31926. if (!this._geometry) {
  31927. return this;
  31928. }
  31929. var oldGeometry = this._geometry;
  31930. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31931. oldGeometry.releaseForMesh(this, true);
  31932. geometry.applyToMesh(this);
  31933. return this;
  31934. };
  31935. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31936. if (totalVertices === void 0) { totalVertices = null; }
  31937. if (updatable === void 0) { updatable = false; }
  31938. if (!this._geometry) {
  31939. var vertexData = new BABYLON.VertexData();
  31940. vertexData.indices = indices;
  31941. var scene = this.getScene();
  31942. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31943. }
  31944. else {
  31945. this._geometry.setIndices(indices, totalVertices, updatable);
  31946. }
  31947. return this;
  31948. };
  31949. /**
  31950. * Update the current index buffer
  31951. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31952. * Returns the Mesh.
  31953. */
  31954. Mesh.prototype.updateIndices = function (indices, offset) {
  31955. if (!this._geometry) {
  31956. return this;
  31957. }
  31958. this._geometry.updateIndices(indices, offset);
  31959. return this;
  31960. };
  31961. /**
  31962. * Invert the geometry to move from a right handed system to a left handed one.
  31963. * Returns the Mesh.
  31964. */
  31965. Mesh.prototype.toLeftHanded = function () {
  31966. if (!this._geometry) {
  31967. return this;
  31968. }
  31969. this._geometry.toLeftHanded();
  31970. return this;
  31971. };
  31972. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31973. if (!this._geometry) {
  31974. return this;
  31975. }
  31976. var engine = this.getScene().getEngine();
  31977. // Wireframe
  31978. var indexToBind;
  31979. if (this._unIndexed) {
  31980. indexToBind = null;
  31981. }
  31982. else {
  31983. switch (fillMode) {
  31984. case BABYLON.Material.PointFillMode:
  31985. indexToBind = null;
  31986. break;
  31987. case BABYLON.Material.WireFrameFillMode:
  31988. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31989. break;
  31990. default:
  31991. case BABYLON.Material.TriangleFillMode:
  31992. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31993. break;
  31994. }
  31995. }
  31996. // VBOs
  31997. this._geometry._bind(effect, indexToBind);
  31998. return this;
  31999. };
  32000. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32001. if (alternate === void 0) { alternate = false; }
  32002. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32003. return this;
  32004. }
  32005. this.onBeforeDrawObservable.notifyObservers(this);
  32006. var scene = this.getScene();
  32007. var engine = scene.getEngine();
  32008. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32009. // or triangles as points
  32010. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32011. }
  32012. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32013. // Triangles as wireframe
  32014. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32015. }
  32016. else {
  32017. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32018. }
  32019. if (scene._isAlternateRenderingEnabled && !alternate) {
  32020. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32021. if (!effect || !scene.activeCamera) {
  32022. return this;
  32023. }
  32024. scene._switchToAlternateCameraConfiguration(true);
  32025. this._effectiveMaterial.bindView(effect);
  32026. this._effectiveMaterial.bindViewProjection(effect);
  32027. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32028. this._draw(subMesh, fillMode, instancesCount, true);
  32029. engine.setViewport(scene.activeCamera.viewport);
  32030. scene._switchToAlternateCameraConfiguration(false);
  32031. this._effectiveMaterial.bindView(effect);
  32032. this._effectiveMaterial.bindViewProjection(effect);
  32033. }
  32034. return this;
  32035. };
  32036. /**
  32037. * Registers for this mesh a javascript function called just before the rendering process.
  32038. * This function is passed the current mesh.
  32039. * Return the Mesh.
  32040. */
  32041. Mesh.prototype.registerBeforeRender = function (func) {
  32042. this.onBeforeRenderObservable.add(func);
  32043. return this;
  32044. };
  32045. /**
  32046. * Disposes a previously registered javascript function called before the rendering.
  32047. * This function is passed the current mesh.
  32048. * Returns the Mesh.
  32049. */
  32050. Mesh.prototype.unregisterBeforeRender = function (func) {
  32051. this.onBeforeRenderObservable.removeCallback(func);
  32052. return this;
  32053. };
  32054. /**
  32055. * Registers for this mesh a javascript function called just after the rendering is complete.
  32056. * This function is passed the current mesh.
  32057. * Returns the Mesh.
  32058. */
  32059. Mesh.prototype.registerAfterRender = function (func) {
  32060. this.onAfterRenderObservable.add(func);
  32061. return this;
  32062. };
  32063. /**
  32064. * Disposes a previously registered javascript function called after the rendering.
  32065. * This function is passed the current mesh.
  32066. * Return the Mesh.
  32067. */
  32068. Mesh.prototype.unregisterAfterRender = function (func) {
  32069. this.onAfterRenderObservable.removeCallback(func);
  32070. return this;
  32071. };
  32072. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32073. var scene = this.getScene();
  32074. this._batchCache.mustReturn = false;
  32075. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32076. this._batchCache.visibleInstances[subMeshId] = null;
  32077. if (this._visibleInstances) {
  32078. var currentRenderId = scene.getRenderId();
  32079. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32080. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32081. var selfRenderId = this._renderId;
  32082. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32083. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32084. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32085. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32086. }
  32087. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32088. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32089. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32090. this._batchCache.mustReturn = true;
  32091. return this._batchCache;
  32092. }
  32093. if (currentRenderId !== selfRenderId) {
  32094. this._batchCache.renderSelf[subMeshId] = false;
  32095. }
  32096. }
  32097. this._renderIdForInstances[subMeshId] = currentRenderId;
  32098. }
  32099. return this._batchCache;
  32100. };
  32101. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32102. var visibleInstances = batch.visibleInstances[subMesh._id];
  32103. if (!visibleInstances) {
  32104. return this;
  32105. }
  32106. var matricesCount = visibleInstances.length + 1;
  32107. var bufferSize = matricesCount * 16 * 4;
  32108. var currentInstancesBufferSize = this._instancesBufferSize;
  32109. var instancesBuffer = this._instancesBuffer;
  32110. while (this._instancesBufferSize < bufferSize) {
  32111. this._instancesBufferSize *= 2;
  32112. }
  32113. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32114. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32115. }
  32116. var offset = 0;
  32117. var instancesCount = 0;
  32118. var world = this.getWorldMatrix();
  32119. if (batch.renderSelf[subMesh._id]) {
  32120. world.copyToArray(this._instancesData, offset);
  32121. offset += 16;
  32122. instancesCount++;
  32123. }
  32124. if (visibleInstances) {
  32125. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32126. var instance = visibleInstances[instanceIndex];
  32127. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32128. offset += 16;
  32129. instancesCount++;
  32130. }
  32131. }
  32132. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32133. if (instancesBuffer) {
  32134. instancesBuffer.dispose();
  32135. }
  32136. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32137. this._instancesBuffer = instancesBuffer;
  32138. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32139. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32140. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32141. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32142. }
  32143. else {
  32144. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32145. }
  32146. this._bind(subMesh, effect, fillMode);
  32147. this._draw(subMesh, fillMode, instancesCount);
  32148. engine.unbindInstanceAttributes();
  32149. return this;
  32150. };
  32151. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32152. var scene = this.getScene();
  32153. var engine = scene.getEngine();
  32154. if (hardwareInstancedRendering) {
  32155. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32156. }
  32157. else {
  32158. if (batch.renderSelf[subMesh._id]) {
  32159. // Draw
  32160. if (onBeforeDraw) {
  32161. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32162. }
  32163. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32164. }
  32165. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32166. if (visibleInstancesForSubMesh) {
  32167. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32168. var instance = visibleInstancesForSubMesh[instanceIndex];
  32169. // World
  32170. var world = instance.getWorldMatrix();
  32171. if (onBeforeDraw) {
  32172. onBeforeDraw(true, world, effectiveMaterial);
  32173. }
  32174. // Draw
  32175. this._draw(subMesh, fillMode);
  32176. }
  32177. }
  32178. }
  32179. return this;
  32180. };
  32181. /**
  32182. * Triggers the draw call for the mesh.
  32183. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32184. * Returns the Mesh.
  32185. */
  32186. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32187. this._checkOcclusionQuery();
  32188. if (this._isOccluded) {
  32189. return this;
  32190. }
  32191. var scene = this.getScene();
  32192. // Managing instances
  32193. var batch = this._getInstancesRenderList(subMesh._id);
  32194. if (batch.mustReturn) {
  32195. return this;
  32196. }
  32197. // Checking geometry state
  32198. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32199. return this;
  32200. }
  32201. this.onBeforeRenderObservable.notifyObservers(this);
  32202. var engine = scene.getEngine();
  32203. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32204. // Material
  32205. var material = subMesh.getMaterial();
  32206. if (!material) {
  32207. return this;
  32208. }
  32209. this._effectiveMaterial = material;
  32210. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32211. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32212. return this;
  32213. }
  32214. }
  32215. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32216. return this;
  32217. }
  32218. // Alpha mode
  32219. if (enableAlphaMode) {
  32220. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32221. }
  32222. // Outline - step 1
  32223. var savedDepthWrite = engine.getDepthWrite();
  32224. if (this.renderOutline) {
  32225. engine.setDepthWrite(false);
  32226. scene.getOutlineRenderer().render(subMesh, batch);
  32227. engine.setDepthWrite(savedDepthWrite);
  32228. }
  32229. var effect;
  32230. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32231. effect = subMesh.effect;
  32232. }
  32233. else {
  32234. effect = this._effectiveMaterial.getEffect();
  32235. }
  32236. if (!effect) {
  32237. return this;
  32238. }
  32239. var sideOrientation = this.overrideMaterialSideOrientation;
  32240. if (sideOrientation == null) {
  32241. sideOrientation = this._effectiveMaterial.sideOrientation;
  32242. if (this._getWorldMatrixDeterminant() < 0) {
  32243. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32244. }
  32245. }
  32246. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32247. if (this._effectiveMaterial.forceDepthWrite) {
  32248. engine.setDepthWrite(true);
  32249. }
  32250. // Bind
  32251. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32252. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32253. this._bind(subMesh, effect, fillMode);
  32254. }
  32255. var world = this.getWorldMatrix();
  32256. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32257. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32258. }
  32259. else {
  32260. this._effectiveMaterial.bind(world, this);
  32261. }
  32262. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32263. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32264. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32265. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32266. }
  32267. // Draw
  32268. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32269. // Unbind
  32270. this._effectiveMaterial.unbind();
  32271. // Outline - step 2
  32272. if (this.renderOutline && savedDepthWrite) {
  32273. engine.setDepthWrite(true);
  32274. engine.setColorWrite(false);
  32275. scene.getOutlineRenderer().render(subMesh, batch);
  32276. engine.setColorWrite(true);
  32277. }
  32278. // Overlay
  32279. if (this.renderOverlay) {
  32280. var currentMode = engine.getAlphaMode();
  32281. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32282. scene.getOutlineRenderer().render(subMesh, batch, true);
  32283. engine.setAlphaMode(currentMode);
  32284. }
  32285. this.onAfterRenderObservable.notifyObservers(this);
  32286. return this;
  32287. };
  32288. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32289. if (isInstance && effectiveMaterial) {
  32290. effectiveMaterial.bindOnlyWorldMatrix(world);
  32291. }
  32292. };
  32293. /**
  32294. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32295. */
  32296. Mesh.prototype.getEmittedParticleSystems = function () {
  32297. var results = new Array();
  32298. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32299. var particleSystem = this.getScene().particleSystems[index];
  32300. if (particleSystem.emitter === this) {
  32301. results.push(particleSystem);
  32302. }
  32303. }
  32304. return results;
  32305. };
  32306. /**
  32307. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32308. */
  32309. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32310. var results = new Array();
  32311. var descendants = this.getDescendants();
  32312. descendants.push(this);
  32313. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32314. var particleSystem = this.getScene().particleSystems[index];
  32315. var emitter = particleSystem.emitter;
  32316. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32317. results.push(particleSystem);
  32318. }
  32319. }
  32320. return results;
  32321. };
  32322. /**
  32323. * Normalize matrix weights so that all vertices have a total weight set to 1
  32324. */
  32325. Mesh.prototype.cleanMatrixWeights = function () {
  32326. var epsilon = 1e-3;
  32327. var noInfluenceBoneIndex = 0.0;
  32328. if (this.skeleton) {
  32329. noInfluenceBoneIndex = this.skeleton.bones.length;
  32330. }
  32331. else {
  32332. return;
  32333. }
  32334. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32335. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32336. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32337. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32338. var influencers = this.numBoneInfluencers;
  32339. var size = matricesWeights.length;
  32340. for (var i = 0; i < size; i += 4) {
  32341. var weight = 0.0;
  32342. var firstZeroWeight = -1;
  32343. for (var j = 0; j < 4; j++) {
  32344. var w = matricesWeights[i + j];
  32345. weight += w;
  32346. if (w < epsilon && firstZeroWeight < 0) {
  32347. firstZeroWeight = j;
  32348. }
  32349. }
  32350. if (matricesWeightsExtra) {
  32351. for (var j = 0; j < 4; j++) {
  32352. var w = matricesWeightsExtra[i + j];
  32353. weight += w;
  32354. if (w < epsilon && firstZeroWeight < 0) {
  32355. firstZeroWeight = j + 4;
  32356. }
  32357. }
  32358. }
  32359. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32360. firstZeroWeight = influencers - 1;
  32361. }
  32362. if (weight > epsilon) {
  32363. var mweight = 1.0 / weight;
  32364. for (var j = 0; j < 4; j++) {
  32365. matricesWeights[i + j] *= mweight;
  32366. }
  32367. if (matricesWeightsExtra) {
  32368. for (var j = 0; j < 4; j++) {
  32369. matricesWeightsExtra[i + j] *= mweight;
  32370. }
  32371. }
  32372. }
  32373. else {
  32374. if (firstZeroWeight >= 4) {
  32375. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32376. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32377. }
  32378. else {
  32379. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32380. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32381. }
  32382. }
  32383. }
  32384. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32385. if (matricesIndicesExtra) {
  32386. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32387. }
  32388. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32389. if (matricesWeightsExtra) {
  32390. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32391. }
  32392. };
  32393. Mesh.prototype._checkDelayState = function () {
  32394. var scene = this.getScene();
  32395. if (this._geometry) {
  32396. this._geometry.load(scene);
  32397. }
  32398. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32400. this._queueLoad(scene);
  32401. }
  32402. return this;
  32403. };
  32404. Mesh.prototype._queueLoad = function (scene) {
  32405. var _this = this;
  32406. scene._addPendingData(this);
  32407. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32408. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32409. if (data instanceof ArrayBuffer) {
  32410. _this._delayLoadingFunction(data, _this);
  32411. }
  32412. else {
  32413. _this._delayLoadingFunction(JSON.parse(data), _this);
  32414. }
  32415. _this.instances.forEach(function (instance) {
  32416. instance._syncSubMeshes();
  32417. });
  32418. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32419. scene._removePendingData(_this);
  32420. }, function () { }, scene.database, getBinaryData);
  32421. return this;
  32422. };
  32423. /**
  32424. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32425. */
  32426. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32427. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32428. return false;
  32429. }
  32430. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32431. return false;
  32432. }
  32433. this._checkDelayState();
  32434. return true;
  32435. };
  32436. /**
  32437. * Sets the mesh material by the material or multiMaterial `id` property.
  32438. * The material `id` is a string identifying the material or the multiMaterial.
  32439. * This method returns the Mesh.
  32440. */
  32441. Mesh.prototype.setMaterialByID = function (id) {
  32442. var materials = this.getScene().materials;
  32443. var index;
  32444. for (index = materials.length - 1; index > -1; index--) {
  32445. if (materials[index].id === id) {
  32446. this.material = materials[index];
  32447. return this;
  32448. }
  32449. }
  32450. // Multi
  32451. var multiMaterials = this.getScene().multiMaterials;
  32452. for (index = multiMaterials.length - 1; index > -1; index--) {
  32453. if (multiMaterials[index].id === id) {
  32454. this.material = multiMaterials[index];
  32455. return this;
  32456. }
  32457. }
  32458. return this;
  32459. };
  32460. /**
  32461. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32462. */
  32463. Mesh.prototype.getAnimatables = function () {
  32464. var results = new Array();
  32465. if (this.material) {
  32466. results.push(this.material);
  32467. }
  32468. if (this.skeleton) {
  32469. results.push(this.skeleton);
  32470. }
  32471. return results;
  32472. };
  32473. /**
  32474. * Modifies the mesh geometry according to the passed transformation matrix.
  32475. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32476. * The mesh normals are modified accordingly the same transformation.
  32477. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32478. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32479. * Returns the Mesh.
  32480. */
  32481. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32482. // Position
  32483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32484. return this;
  32485. }
  32486. var submeshes = this.subMeshes.splice(0);
  32487. this._resetPointsArrayCache();
  32488. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32489. var temp = new Array();
  32490. var index;
  32491. for (index = 0; index < data.length; index += 3) {
  32492. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32493. }
  32494. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32495. // Normals
  32496. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32497. return this;
  32498. }
  32499. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32500. temp = [];
  32501. for (index = 0; index < data.length; index += 3) {
  32502. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32503. }
  32504. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32505. // flip faces?
  32506. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32507. this.flipFaces();
  32508. }
  32509. // Restore submeshes
  32510. this.releaseSubMeshes();
  32511. this.subMeshes = submeshes;
  32512. return this;
  32513. };
  32514. /**
  32515. * Modifies the mesh geometry according to its own current World Matrix.
  32516. * The mesh World Matrix is then reset.
  32517. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32518. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32519. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32520. * Returns the Mesh.
  32521. */
  32522. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32523. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32524. this.scaling.copyFromFloats(1, 1, 1);
  32525. this.position.copyFromFloats(0, 0, 0);
  32526. this.rotation.copyFromFloats(0, 0, 0);
  32527. //only if quaternion is already set
  32528. if (this.rotationQuaternion) {
  32529. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32530. }
  32531. this._worldMatrix = BABYLON.Matrix.Identity();
  32532. return this;
  32533. };
  32534. Object.defineProperty(Mesh.prototype, "_positions", {
  32535. // Cache
  32536. get: function () {
  32537. if (this._geometry) {
  32538. return this._geometry._positions;
  32539. }
  32540. return null;
  32541. },
  32542. enumerable: true,
  32543. configurable: true
  32544. });
  32545. Mesh.prototype._resetPointsArrayCache = function () {
  32546. if (this._geometry) {
  32547. this._geometry._resetPointsArrayCache();
  32548. }
  32549. return this;
  32550. };
  32551. Mesh.prototype._generatePointsArray = function () {
  32552. if (this._geometry) {
  32553. return this._geometry._generatePointsArray();
  32554. }
  32555. return false;
  32556. };
  32557. /**
  32558. * Returns a new Mesh object generated from the current mesh properties.
  32559. * This method must not get confused with createInstance().
  32560. * The parameter `name` is a string, the name given to the new mesh.
  32561. * The optional parameter `newParent` can be any Node object (default `null`).
  32562. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32563. * 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.
  32564. */
  32565. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32566. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32567. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32568. };
  32569. /**
  32570. * Releases resources associated with this mesh.
  32571. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32572. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32573. */
  32574. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32575. var _this = this;
  32576. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32577. this.morphTargetManager = null;
  32578. if (this._geometry) {
  32579. this._geometry.releaseForMesh(this, true);
  32580. }
  32581. // Sources
  32582. var meshes = this.getScene().meshes;
  32583. meshes.forEach(function (abstractMesh) {
  32584. var mesh = abstractMesh;
  32585. if (mesh._source && mesh._source === _this) {
  32586. mesh._source = null;
  32587. }
  32588. });
  32589. this._source = null;
  32590. // Instances
  32591. if (this._instancesBuffer) {
  32592. this._instancesBuffer.dispose();
  32593. this._instancesBuffer = null;
  32594. }
  32595. while (this.instances.length) {
  32596. this.instances[0].dispose();
  32597. }
  32598. // Effect layers.
  32599. var effectLayers = this.getScene().effectLayers;
  32600. for (var i = 0; i < effectLayers.length; i++) {
  32601. var effectLayer = effectLayers[i];
  32602. if (effectLayer) {
  32603. effectLayer._disposeMesh(this);
  32604. }
  32605. }
  32606. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32607. };
  32608. /**
  32609. * Modifies the mesh geometry according to a displacement map.
  32610. * 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.
  32611. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32612. * This method returns nothing.
  32613. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32614. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32615. * 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.
  32616. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32617. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32618. *
  32619. * Returns the Mesh.
  32620. */
  32621. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32622. var _this = this;
  32623. var scene = this.getScene();
  32624. var onload = function (img) {
  32625. // Getting height map data
  32626. var canvas = document.createElement("canvas");
  32627. var context = canvas.getContext("2d");
  32628. var heightMapWidth = img.width;
  32629. var heightMapHeight = img.height;
  32630. canvas.width = heightMapWidth;
  32631. canvas.height = heightMapHeight;
  32632. context.drawImage(img, 0, 0);
  32633. // Create VertexData from map data
  32634. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32635. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32636. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32637. //execute success callback, if set
  32638. if (onSuccess) {
  32639. onSuccess(_this);
  32640. }
  32641. };
  32642. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32643. return this;
  32644. };
  32645. /**
  32646. * Modifies the mesh geometry according to a displacementMap buffer.
  32647. * 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.
  32648. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32649. * This method returns nothing.
  32650. * 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.
  32651. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32652. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32653. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32654. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32655. *
  32656. * Returns the Mesh.
  32657. */
  32658. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32659. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32660. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32661. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32662. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32663. return this;
  32664. }
  32665. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32666. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32667. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32668. var position = BABYLON.Vector3.Zero();
  32669. var normal = BABYLON.Vector3.Zero();
  32670. var uv = BABYLON.Vector2.Zero();
  32671. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32672. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32673. for (var index = 0; index < positions.length; index += 3) {
  32674. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32675. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32676. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32677. // Compute height
  32678. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32679. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32680. var pos = (u + v * heightMapWidth) * 4;
  32681. var r = buffer[pos] / 255.0;
  32682. var g = buffer[pos + 1] / 255.0;
  32683. var b = buffer[pos + 2] / 255.0;
  32684. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32685. normal.normalize();
  32686. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32687. position = position.add(normal);
  32688. position.toArray(positions, index);
  32689. }
  32690. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32691. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32692. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32693. return this;
  32694. };
  32695. /**
  32696. * Modify the mesh to get a flat shading rendering.
  32697. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32698. * This method returns the Mesh.
  32699. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32700. */
  32701. Mesh.prototype.convertToFlatShadedMesh = function () {
  32702. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32703. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32704. var kinds = this.getVerticesDataKinds();
  32705. var vbs = {};
  32706. var data = {};
  32707. var newdata = {};
  32708. var updatableNormals = false;
  32709. var kindIndex;
  32710. var kind;
  32711. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32712. kind = kinds[kindIndex];
  32713. var vertexBuffer = this.getVertexBuffer(kind);
  32714. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32715. updatableNormals = vertexBuffer.isUpdatable();
  32716. kinds.splice(kindIndex, 1);
  32717. kindIndex--;
  32718. continue;
  32719. }
  32720. vbs[kind] = vertexBuffer;
  32721. data[kind] = vbs[kind].getData();
  32722. newdata[kind] = [];
  32723. }
  32724. // Save previous submeshes
  32725. var previousSubmeshes = this.subMeshes.slice(0);
  32726. var indices = this.getIndices();
  32727. var totalIndices = this.getTotalIndices();
  32728. // Generating unique vertices per face
  32729. var index;
  32730. for (index = 0; index < totalIndices; index++) {
  32731. var vertexIndex = indices[index];
  32732. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32733. kind = kinds[kindIndex];
  32734. var stride = vbs[kind].getStrideSize();
  32735. for (var offset = 0; offset < stride; offset++) {
  32736. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32737. }
  32738. }
  32739. }
  32740. // Updating faces & normal
  32741. var normals = [];
  32742. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32743. for (index = 0; index < totalIndices; index += 3) {
  32744. indices[index] = index;
  32745. indices[index + 1] = index + 1;
  32746. indices[index + 2] = index + 2;
  32747. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32748. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32749. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32750. var p1p2 = p1.subtract(p2);
  32751. var p3p2 = p3.subtract(p2);
  32752. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32753. // Store same normals for every vertex
  32754. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32755. normals.push(normal.x);
  32756. normals.push(normal.y);
  32757. normals.push(normal.z);
  32758. }
  32759. }
  32760. this.setIndices(indices);
  32761. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32762. // Updating vertex buffers
  32763. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32764. kind = kinds[kindIndex];
  32765. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32766. }
  32767. // Updating submeshes
  32768. this.releaseSubMeshes();
  32769. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32770. var previousOne = previousSubmeshes[submeshIndex];
  32771. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32772. }
  32773. this.synchronizeInstances();
  32774. return this;
  32775. };
  32776. /**
  32777. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32778. * In other words, more vertices, no more indices and a single bigger VBO.
  32779. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32780. * Returns the Mesh.
  32781. */
  32782. Mesh.prototype.convertToUnIndexedMesh = function () {
  32783. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32784. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32785. var kinds = this.getVerticesDataKinds();
  32786. var vbs = {};
  32787. var data = {};
  32788. var newdata = {};
  32789. var kindIndex;
  32790. var kind;
  32791. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32792. kind = kinds[kindIndex];
  32793. var vertexBuffer = this.getVertexBuffer(kind);
  32794. vbs[kind] = vertexBuffer;
  32795. data[kind] = vbs[kind].getData();
  32796. newdata[kind] = [];
  32797. }
  32798. // Save previous submeshes
  32799. var previousSubmeshes = this.subMeshes.slice(0);
  32800. var indices = this.getIndices();
  32801. var totalIndices = this.getTotalIndices();
  32802. // Generating unique vertices per face
  32803. var index;
  32804. for (index = 0; index < totalIndices; index++) {
  32805. var vertexIndex = indices[index];
  32806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32807. kind = kinds[kindIndex];
  32808. var stride = vbs[kind].getStrideSize();
  32809. for (var offset = 0; offset < stride; offset++) {
  32810. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32811. }
  32812. }
  32813. }
  32814. // Updating indices
  32815. for (index = 0; index < totalIndices; index += 3) {
  32816. indices[index] = index;
  32817. indices[index + 1] = index + 1;
  32818. indices[index + 2] = index + 2;
  32819. }
  32820. this.setIndices(indices);
  32821. // Updating vertex buffers
  32822. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32823. kind = kinds[kindIndex];
  32824. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32825. }
  32826. // Updating submeshes
  32827. this.releaseSubMeshes();
  32828. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32829. var previousOne = previousSubmeshes[submeshIndex];
  32830. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32831. }
  32832. this._unIndexed = true;
  32833. this.synchronizeInstances();
  32834. return this;
  32835. };
  32836. /**
  32837. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32838. * This method returns the Mesh.
  32839. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32840. */
  32841. Mesh.prototype.flipFaces = function (flipNormals) {
  32842. if (flipNormals === void 0) { flipNormals = false; }
  32843. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32844. var i;
  32845. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32846. for (i = 0; i < vertex_data.normals.length; i++) {
  32847. vertex_data.normals[i] *= -1;
  32848. }
  32849. }
  32850. if (vertex_data.indices) {
  32851. var temp;
  32852. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32853. // reassign indices
  32854. temp = vertex_data.indices[i + 1];
  32855. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32856. vertex_data.indices[i + 2] = temp;
  32857. }
  32858. }
  32859. vertex_data.applyToMesh(this);
  32860. return this;
  32861. };
  32862. // Instances
  32863. /**
  32864. * Creates a new InstancedMesh object from the mesh model.
  32865. * An instance shares the same properties and the same material than its model.
  32866. * Only these properties of each instance can then be set individually :
  32867. * - position
  32868. * - rotation
  32869. * - rotationQuaternion
  32870. * - setPivotMatrix
  32871. * - scaling
  32872. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32873. * Warning : this method is not supported for Line mesh and LineSystem
  32874. */
  32875. Mesh.prototype.createInstance = function (name) {
  32876. return new BABYLON.InstancedMesh(name, this);
  32877. };
  32878. /**
  32879. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32880. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32881. * This method returns the Mesh.
  32882. */
  32883. Mesh.prototype.synchronizeInstances = function () {
  32884. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32885. var instance = this.instances[instanceIndex];
  32886. instance._syncSubMeshes();
  32887. }
  32888. return this;
  32889. };
  32890. /**
  32891. * Simplify the mesh according to the given array of settings.
  32892. * Function will return immediately and will simplify async. It returns the Mesh.
  32893. * @param settings a collection of simplification settings.
  32894. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32895. * @param type the type of simplification to run.
  32896. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32897. */
  32898. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32899. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32900. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32901. this.getScene().simplificationQueue.addTask({
  32902. settings: settings,
  32903. parallelProcessing: parallelProcessing,
  32904. mesh: this,
  32905. simplificationType: simplificationType,
  32906. successCallback: successCallback
  32907. });
  32908. return this;
  32909. };
  32910. /**
  32911. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32912. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32913. * This should be used together with the simplification to avoid disappearing triangles.
  32914. * Returns the Mesh.
  32915. * @param successCallback an optional success callback to be called after the optimization finished.
  32916. */
  32917. Mesh.prototype.optimizeIndices = function (successCallback) {
  32918. var _this = this;
  32919. var indices = this.getIndices();
  32920. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32921. if (!positions || !indices) {
  32922. return this;
  32923. }
  32924. var vectorPositions = new Array();
  32925. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32926. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32927. }
  32928. var dupes = new Array();
  32929. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32930. var realPos = vectorPositions.length - 1 - iteration;
  32931. var testedPosition = vectorPositions[realPos];
  32932. for (var j = 0; j < realPos; ++j) {
  32933. var againstPosition = vectorPositions[j];
  32934. if (testedPosition.equals(againstPosition)) {
  32935. dupes[realPos] = j;
  32936. break;
  32937. }
  32938. }
  32939. }, function () {
  32940. for (var i = 0; i < indices.length; ++i) {
  32941. indices[i] = dupes[indices[i]] || indices[i];
  32942. }
  32943. //indices are now reordered
  32944. var originalSubMeshes = _this.subMeshes.slice(0);
  32945. _this.setIndices(indices);
  32946. _this.subMeshes = originalSubMeshes;
  32947. if (successCallback) {
  32948. successCallback(_this);
  32949. }
  32950. });
  32951. return this;
  32952. };
  32953. Mesh.prototype.serialize = function (serializationObject) {
  32954. serializationObject.name = this.name;
  32955. serializationObject.id = this.id;
  32956. serializationObject.type = this.getClassName();
  32957. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32958. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32959. }
  32960. serializationObject.position = this.position.asArray();
  32961. if (this.rotationQuaternion) {
  32962. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32963. }
  32964. else if (this.rotation) {
  32965. serializationObject.rotation = this.rotation.asArray();
  32966. }
  32967. serializationObject.scaling = this.scaling.asArray();
  32968. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32969. serializationObject.isEnabled = this.isEnabled(false);
  32970. serializationObject.isVisible = this.isVisible;
  32971. serializationObject.infiniteDistance = this.infiniteDistance;
  32972. serializationObject.pickable = this.isPickable;
  32973. serializationObject.receiveShadows = this.receiveShadows;
  32974. serializationObject.billboardMode = this.billboardMode;
  32975. serializationObject.visibility = this.visibility;
  32976. serializationObject.checkCollisions = this.checkCollisions;
  32977. serializationObject.isBlocker = this.isBlocker;
  32978. // Parent
  32979. if (this.parent) {
  32980. serializationObject.parentId = this.parent.id;
  32981. }
  32982. // Geometry
  32983. serializationObject.isUnIndexed = this.isUnIndexed;
  32984. var geometry = this._geometry;
  32985. if (geometry) {
  32986. var geometryId = geometry.id;
  32987. serializationObject.geometryId = geometryId;
  32988. // SubMeshes
  32989. serializationObject.subMeshes = [];
  32990. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32991. var subMesh = this.subMeshes[subIndex];
  32992. serializationObject.subMeshes.push({
  32993. materialIndex: subMesh.materialIndex,
  32994. verticesStart: subMesh.verticesStart,
  32995. verticesCount: subMesh.verticesCount,
  32996. indexStart: subMesh.indexStart,
  32997. indexCount: subMesh.indexCount
  32998. });
  32999. }
  33000. }
  33001. // Material
  33002. if (this.material) {
  33003. serializationObject.materialId = this.material.id;
  33004. }
  33005. else {
  33006. this.material = null;
  33007. }
  33008. // Morph targets
  33009. if (this.morphTargetManager) {
  33010. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33011. }
  33012. // Skeleton
  33013. if (this.skeleton) {
  33014. serializationObject.skeletonId = this.skeleton.id;
  33015. }
  33016. // Physics
  33017. //TODO implement correct serialization for physics impostors.
  33018. var impostor = this.getPhysicsImpostor();
  33019. if (impostor) {
  33020. serializationObject.physicsMass = impostor.getParam("mass");
  33021. serializationObject.physicsFriction = impostor.getParam("friction");
  33022. serializationObject.physicsRestitution = impostor.getParam("mass");
  33023. serializationObject.physicsImpostor = impostor.type;
  33024. }
  33025. // Metadata
  33026. if (this.metadata) {
  33027. serializationObject.metadata = this.metadata;
  33028. }
  33029. // Instances
  33030. serializationObject.instances = [];
  33031. for (var index = 0; index < this.instances.length; index++) {
  33032. var instance = this.instances[index];
  33033. var serializationInstance = {
  33034. name: instance.name,
  33035. id: instance.id,
  33036. position: instance.position.asArray(),
  33037. scaling: instance.scaling.asArray()
  33038. };
  33039. if (instance.rotationQuaternion) {
  33040. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33041. }
  33042. else if (instance.rotation) {
  33043. serializationInstance.rotation = instance.rotation.asArray();
  33044. }
  33045. serializationObject.instances.push(serializationInstance);
  33046. // Animations
  33047. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33048. serializationInstance.ranges = instance.serializeAnimationRanges();
  33049. }
  33050. //
  33051. // Animations
  33052. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33053. serializationObject.ranges = this.serializeAnimationRanges();
  33054. // Layer mask
  33055. serializationObject.layerMask = this.layerMask;
  33056. // Alpha
  33057. serializationObject.alphaIndex = this.alphaIndex;
  33058. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33059. // Overlay
  33060. serializationObject.overlayAlpha = this.overlayAlpha;
  33061. serializationObject.overlayColor = this.overlayColor.asArray();
  33062. serializationObject.renderOverlay = this.renderOverlay;
  33063. // Fog
  33064. serializationObject.applyFog = this.applyFog;
  33065. // Action Manager
  33066. if (this.actionManager) {
  33067. serializationObject.actions = this.actionManager.serialize(this.name);
  33068. }
  33069. };
  33070. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33071. if (!this.geometry) {
  33072. return;
  33073. }
  33074. this._markSubMeshesAsAttributesDirty();
  33075. var morphTargetManager = this._morphTargetManager;
  33076. if (morphTargetManager && morphTargetManager.vertexCount) {
  33077. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33078. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33079. this.morphTargetManager = null;
  33080. return;
  33081. }
  33082. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33083. var morphTarget = morphTargetManager.getActiveTarget(index);
  33084. var positions = morphTarget.getPositions();
  33085. if (!positions) {
  33086. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33087. return;
  33088. }
  33089. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33090. var normals = morphTarget.getNormals();
  33091. if (normals) {
  33092. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33093. }
  33094. var tangents = morphTarget.getTangents();
  33095. if (tangents) {
  33096. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33097. }
  33098. }
  33099. }
  33100. else {
  33101. var index = 0;
  33102. // Positions
  33103. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33104. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33105. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33106. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33107. }
  33108. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33109. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33110. }
  33111. index++;
  33112. }
  33113. }
  33114. };
  33115. // Statics
  33116. /**
  33117. * Returns a new Mesh object parsed from the source provided.
  33118. * The parameter `parsedMesh` is the source.
  33119. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33120. */
  33121. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33122. var mesh;
  33123. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33124. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33125. }
  33126. else {
  33127. mesh = new Mesh(parsedMesh.name, scene);
  33128. }
  33129. mesh.id = parsedMesh.id;
  33130. if (BABYLON.Tags) {
  33131. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33132. }
  33133. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33134. if (parsedMesh.metadata !== undefined) {
  33135. mesh.metadata = parsedMesh.metadata;
  33136. }
  33137. if (parsedMesh.rotationQuaternion) {
  33138. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33139. }
  33140. else if (parsedMesh.rotation) {
  33141. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33142. }
  33143. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33144. if (parsedMesh.localMatrix) {
  33145. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33146. }
  33147. else if (parsedMesh.pivotMatrix) {
  33148. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33149. }
  33150. mesh.setEnabled(parsedMesh.isEnabled);
  33151. mesh.isVisible = parsedMesh.isVisible;
  33152. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33153. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33154. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33155. if (parsedMesh.applyFog !== undefined) {
  33156. mesh.applyFog = parsedMesh.applyFog;
  33157. }
  33158. if (parsedMesh.pickable !== undefined) {
  33159. mesh.isPickable = parsedMesh.pickable;
  33160. }
  33161. if (parsedMesh.alphaIndex !== undefined) {
  33162. mesh.alphaIndex = parsedMesh.alphaIndex;
  33163. }
  33164. mesh.receiveShadows = parsedMesh.receiveShadows;
  33165. mesh.billboardMode = parsedMesh.billboardMode;
  33166. if (parsedMesh.visibility !== undefined) {
  33167. mesh.visibility = parsedMesh.visibility;
  33168. }
  33169. mesh.checkCollisions = parsedMesh.checkCollisions;
  33170. if (parsedMesh.isBlocker !== undefined) {
  33171. mesh.isBlocker = parsedMesh.isBlocker;
  33172. }
  33173. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33174. // freezeWorldMatrix
  33175. if (parsedMesh.freezeWorldMatrix) {
  33176. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33177. }
  33178. // Parent
  33179. if (parsedMesh.parentId) {
  33180. mesh._waitingParentId = parsedMesh.parentId;
  33181. }
  33182. // Actions
  33183. if (parsedMesh.actions !== undefined) {
  33184. mesh._waitingActions = parsedMesh.actions;
  33185. }
  33186. // Overlay
  33187. if (parsedMesh.overlayAlpha !== undefined) {
  33188. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33189. }
  33190. if (parsedMesh.overlayColor !== undefined) {
  33191. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33192. }
  33193. if (parsedMesh.renderOverlay !== undefined) {
  33194. mesh.renderOverlay = parsedMesh.renderOverlay;
  33195. }
  33196. // Geometry
  33197. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33198. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33199. if (parsedMesh.delayLoadingFile) {
  33200. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33201. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33202. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33203. if (parsedMesh._binaryInfo) {
  33204. mesh._binaryInfo = parsedMesh._binaryInfo;
  33205. }
  33206. mesh._delayInfo = [];
  33207. if (parsedMesh.hasUVs) {
  33208. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33209. }
  33210. if (parsedMesh.hasUVs2) {
  33211. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33212. }
  33213. if (parsedMesh.hasUVs3) {
  33214. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33215. }
  33216. if (parsedMesh.hasUVs4) {
  33217. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33218. }
  33219. if (parsedMesh.hasUVs5) {
  33220. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33221. }
  33222. if (parsedMesh.hasUVs6) {
  33223. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33224. }
  33225. if (parsedMesh.hasColors) {
  33226. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33227. }
  33228. if (parsedMesh.hasMatricesIndices) {
  33229. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33230. }
  33231. if (parsedMesh.hasMatricesWeights) {
  33232. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33233. }
  33234. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33235. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33236. mesh._checkDelayState();
  33237. }
  33238. }
  33239. else {
  33240. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33241. }
  33242. // Material
  33243. if (parsedMesh.materialId) {
  33244. mesh.setMaterialByID(parsedMesh.materialId);
  33245. }
  33246. else {
  33247. mesh.material = null;
  33248. }
  33249. // Morph targets
  33250. if (parsedMesh.morphTargetManagerId > -1) {
  33251. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33252. }
  33253. // Skeleton
  33254. if (parsedMesh.skeletonId > -1) {
  33255. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33256. if (parsedMesh.numBoneInfluencers) {
  33257. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33258. }
  33259. }
  33260. // Animations
  33261. if (parsedMesh.animations) {
  33262. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33263. var parsedAnimation = parsedMesh.animations[animationIndex];
  33264. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33265. }
  33266. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33267. }
  33268. if (parsedMesh.autoAnimate) {
  33269. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33270. }
  33271. // Layer Mask
  33272. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33273. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33274. }
  33275. else {
  33276. mesh.layerMask = 0x0FFFFFFF;
  33277. }
  33278. // Physics
  33279. if (parsedMesh.physicsImpostor) {
  33280. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33281. mass: parsedMesh.physicsMass,
  33282. friction: parsedMesh.physicsFriction,
  33283. restitution: parsedMesh.physicsRestitution
  33284. }, scene);
  33285. }
  33286. // Instances
  33287. if (parsedMesh.instances) {
  33288. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33289. var parsedInstance = parsedMesh.instances[index];
  33290. var instance = mesh.createInstance(parsedInstance.name);
  33291. if (parsedInstance.id) {
  33292. instance.id = parsedInstance.id;
  33293. }
  33294. if (BABYLON.Tags) {
  33295. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33296. }
  33297. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33298. if (parsedInstance.parentId) {
  33299. instance._waitingParentId = parsedInstance.parentId;
  33300. }
  33301. if (parsedInstance.rotationQuaternion) {
  33302. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33303. }
  33304. else if (parsedInstance.rotation) {
  33305. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33306. }
  33307. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33308. instance.checkCollisions = mesh.checkCollisions;
  33309. if (parsedMesh.animations) {
  33310. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33311. parsedAnimation = parsedMesh.animations[animationIndex];
  33312. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33313. }
  33314. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33315. }
  33316. }
  33317. }
  33318. return mesh;
  33319. };
  33320. /**
  33321. * Creates a ribbon mesh.
  33322. * Please consider using the same method from the MeshBuilder class instead.
  33323. * 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.
  33324. *
  33325. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33326. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33327. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33328. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33329. * 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.
  33330. * 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.
  33331. * 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
  33332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33333. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33335. */
  33336. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33337. if (closeArray === void 0) { closeArray = false; }
  33338. if (updatable === void 0) { updatable = false; }
  33339. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33340. pathArray: pathArray,
  33341. closeArray: closeArray,
  33342. closePath: closePath,
  33343. offset: offset,
  33344. updatable: updatable,
  33345. sideOrientation: sideOrientation,
  33346. instance: instance
  33347. }, scene);
  33348. };
  33349. /**
  33350. * Creates a plane polygonal mesh. By default, this is a disc.
  33351. * Please consider using the same method from the MeshBuilder class instead.
  33352. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33353. * 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.
  33354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33355. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33357. */
  33358. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33359. if (scene === void 0) { scene = null; }
  33360. var options = {
  33361. radius: radius,
  33362. tessellation: tessellation,
  33363. sideOrientation: sideOrientation,
  33364. updatable: updatable
  33365. };
  33366. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33367. };
  33368. /**
  33369. * Creates a box mesh.
  33370. * Please consider using the same method from the MeshBuilder class instead.
  33371. * The parameter `size` sets the size (float) of each box side (default 1).
  33372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33373. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33375. */
  33376. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33377. if (scene === void 0) { scene = null; }
  33378. var options = {
  33379. size: size,
  33380. sideOrientation: sideOrientation,
  33381. updatable: updatable
  33382. };
  33383. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33384. };
  33385. /**
  33386. * Creates a sphere mesh.
  33387. * Please consider using the same method from the MeshBuilder class instead.
  33388. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33389. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33391. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33393. */
  33394. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33395. var options = {
  33396. segments: segments,
  33397. diameterX: diameter,
  33398. diameterY: diameter,
  33399. diameterZ: diameter,
  33400. sideOrientation: sideOrientation,
  33401. updatable: updatable
  33402. };
  33403. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33404. };
  33405. /**
  33406. * Creates a cylinder or a cone mesh.
  33407. * Please consider using the same method from the MeshBuilder class instead.
  33408. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33409. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33410. * 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.
  33411. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33412. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33414. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33416. */
  33417. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33418. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33419. if (scene !== undefined) {
  33420. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33421. updatable = scene;
  33422. }
  33423. scene = subdivisions;
  33424. subdivisions = 1;
  33425. }
  33426. var options = {
  33427. height: height,
  33428. diameterTop: diameterTop,
  33429. diameterBottom: diameterBottom,
  33430. tessellation: tessellation,
  33431. subdivisions: subdivisions,
  33432. sideOrientation: sideOrientation,
  33433. updatable: updatable
  33434. };
  33435. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33436. };
  33437. // Torus (Code from SharpDX.org)
  33438. /**
  33439. * Creates a torus mesh.
  33440. * Please consider using the same method from the MeshBuilder class instead.
  33441. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33442. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33443. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33445. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33447. */
  33448. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33449. var options = {
  33450. diameter: diameter,
  33451. thickness: thickness,
  33452. tessellation: tessellation,
  33453. sideOrientation: sideOrientation,
  33454. updatable: updatable
  33455. };
  33456. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33457. };
  33458. /**
  33459. * Creates a torus knot mesh.
  33460. * Please consider using the same method from the MeshBuilder class instead.
  33461. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33462. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33463. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33464. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33466. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33468. */
  33469. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33470. var options = {
  33471. radius: radius,
  33472. tube: tube,
  33473. radialSegments: radialSegments,
  33474. tubularSegments: tubularSegments,
  33475. p: p,
  33476. q: q,
  33477. sideOrientation: sideOrientation,
  33478. updatable: updatable
  33479. };
  33480. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33481. };
  33482. /**
  33483. * Creates a line mesh.
  33484. * Please consider using the same method from the MeshBuilder class instead.
  33485. * 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.
  33486. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33487. * The parameter `points` is an array successive Vector3.
  33488. * 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
  33489. * When updating an instance, remember that only point positions can change, not the number of points.
  33490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33491. */
  33492. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33493. if (scene === void 0) { scene = null; }
  33494. if (updatable === void 0) { updatable = false; }
  33495. if (instance === void 0) { instance = null; }
  33496. var options = {
  33497. points: points,
  33498. updatable: updatable,
  33499. instance: instance
  33500. };
  33501. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33502. };
  33503. /**
  33504. * Creates a dashed line mesh.
  33505. * Please consider using the same method from the MeshBuilder class instead.
  33506. * 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.
  33507. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33508. * The parameter `points` is an array successive Vector3.
  33509. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33510. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33511. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33512. * 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
  33513. * When updating an instance, remember that only point positions can change, not the number of points.
  33514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33515. */
  33516. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33517. if (scene === void 0) { scene = null; }
  33518. var options = {
  33519. points: points,
  33520. dashSize: dashSize,
  33521. gapSize: gapSize,
  33522. dashNb: dashNb,
  33523. updatable: updatable,
  33524. instance: instance
  33525. };
  33526. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33527. };
  33528. /**
  33529. * Creates a polygon mesh.
  33530. * Please consider using the same method from the MeshBuilder class instead.
  33531. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33532. * 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.
  33533. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33535. * Remember you can only change the shape positions, not their number when updating a polygon.
  33536. */
  33537. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33538. var options = {
  33539. shape: shape,
  33540. holes: holes,
  33541. updatable: updatable,
  33542. sideOrientation: sideOrientation
  33543. };
  33544. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33545. };
  33546. /**
  33547. * Creates an extruded polygon mesh, with depth in the Y direction.
  33548. * Please consider using the same method from the MeshBuilder class instead.
  33549. */
  33550. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33551. var options = {
  33552. shape: shape,
  33553. holes: holes,
  33554. depth: depth,
  33555. updatable: updatable,
  33556. sideOrientation: sideOrientation
  33557. };
  33558. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33559. };
  33560. /**
  33561. * Creates an extruded shape mesh.
  33562. * 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.
  33563. * Please consider using the same method from the MeshBuilder class instead.
  33564. *
  33565. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33566. * 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
  33567. * extruded along the Z axis.
  33568. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33569. * 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.
  33570. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33571. * 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
  33572. * 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
  33573. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33574. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33575. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33577. */
  33578. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33579. if (scene === void 0) { scene = null; }
  33580. var options = {
  33581. shape: shape,
  33582. path: path,
  33583. scale: scale,
  33584. rotation: rotation,
  33585. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33586. sideOrientation: sideOrientation,
  33587. instance: instance,
  33588. updatable: updatable
  33589. };
  33590. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33591. };
  33592. /**
  33593. * Creates an custom extruded shape mesh.
  33594. * 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.
  33595. * Please consider using the same method from the MeshBuilder class instead.
  33596. *
  33597. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33598. * 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
  33599. * extruded along the Z axis.
  33600. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33601. * 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
  33602. * and the distance of this point from the begining of the path :
  33603. * ```javascript
  33604. * var rotationFunction = function(i, distance) {
  33605. * // do things
  33606. * return rotationValue; }
  33607. * ```
  33608. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33609. * 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
  33610. * and the distance of this point from the begining of the path :
  33611. * ```javascript
  33612. * var scaleFunction = function(i, distance) {
  33613. * // do things
  33614. * return scaleValue;}
  33615. * ```
  33616. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33617. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33618. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33619. * 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
  33620. * 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
  33621. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33623. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33625. */
  33626. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33627. var options = {
  33628. shape: shape,
  33629. path: path,
  33630. scaleFunction: scaleFunction,
  33631. rotationFunction: rotationFunction,
  33632. ribbonCloseArray: ribbonCloseArray,
  33633. ribbonClosePath: ribbonClosePath,
  33634. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33635. sideOrientation: sideOrientation,
  33636. instance: instance,
  33637. updatable: updatable
  33638. };
  33639. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33640. };
  33641. /**
  33642. * Creates lathe mesh.
  33643. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33644. * Please consider using the same method from the MeshBuilder class instead.
  33645. * 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
  33646. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33647. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33648. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33650. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33652. */
  33653. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33654. var options = {
  33655. shape: shape,
  33656. radius: radius,
  33657. tessellation: tessellation,
  33658. sideOrientation: sideOrientation,
  33659. updatable: updatable
  33660. };
  33661. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33662. };
  33663. /**
  33664. * Creates a plane mesh.
  33665. * Please consider using the same method from the MeshBuilder class instead.
  33666. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33668. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33670. */
  33671. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33672. var options = {
  33673. size: size,
  33674. width: size,
  33675. height: size,
  33676. sideOrientation: sideOrientation,
  33677. updatable: updatable
  33678. };
  33679. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33680. };
  33681. /**
  33682. * Creates a ground mesh.
  33683. * Please consider using the same method from the MeshBuilder class instead.
  33684. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33685. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33687. */
  33688. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33689. var options = {
  33690. width: width,
  33691. height: height,
  33692. subdivisions: subdivisions,
  33693. updatable: updatable
  33694. };
  33695. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33696. };
  33697. /**
  33698. * Creates a tiled ground mesh.
  33699. * Please consider using the same method from the MeshBuilder class instead.
  33700. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33701. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33702. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33703. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33704. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33705. * numbers of subdivisions on the ground width and height of each tile.
  33706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33707. */
  33708. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33709. var options = {
  33710. xmin: xmin,
  33711. zmin: zmin,
  33712. xmax: xmax,
  33713. zmax: zmax,
  33714. subdivisions: subdivisions,
  33715. precision: precision,
  33716. updatable: updatable
  33717. };
  33718. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33719. };
  33720. /**
  33721. * Creates a ground mesh from a height map.
  33722. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33723. * Please consider using the same method from the MeshBuilder class instead.
  33724. * The parameter `url` sets the URL of the height map image resource.
  33725. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33726. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33727. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33728. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33729. * 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).
  33730. * This function is passed the newly built mesh :
  33731. * ```javascript
  33732. * function(mesh) { // do things
  33733. * return; }
  33734. * ```
  33735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33736. */
  33737. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33738. var options = {
  33739. width: width,
  33740. height: height,
  33741. subdivisions: subdivisions,
  33742. minHeight: minHeight,
  33743. maxHeight: maxHeight,
  33744. updatable: updatable,
  33745. onReady: onReady
  33746. };
  33747. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33748. };
  33749. /**
  33750. * Creates a tube mesh.
  33751. * 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.
  33752. * Please consider using the same method from the MeshBuilder class instead.
  33753. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33754. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33755. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33756. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33757. * 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.
  33758. * It must return a radius value (positive float) :
  33759. * ```javascript
  33760. * var radiusFunction = function(i, distance) {
  33761. * // do things
  33762. * return radius; }
  33763. * ```
  33764. * 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
  33765. * 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
  33766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33767. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33769. */
  33770. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33771. var options = {
  33772. path: path,
  33773. radius: radius,
  33774. tessellation: tessellation,
  33775. radiusFunction: radiusFunction,
  33776. arc: 1,
  33777. cap: cap,
  33778. updatable: updatable,
  33779. sideOrientation: sideOrientation,
  33780. instance: instance
  33781. };
  33782. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33783. };
  33784. /**
  33785. * Creates a polyhedron mesh.
  33786. * Please consider using the same method from the MeshBuilder class instead.
  33787. * 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
  33788. * to choose the wanted type.
  33789. * The parameter `size` (positive float, default 1) sets the polygon size.
  33790. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33791. * 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`.
  33792. * 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
  33793. * 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)`).
  33794. * 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
  33795. * 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.
  33796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33797. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33799. */
  33800. Mesh.CreatePolyhedron = function (name, options, scene) {
  33801. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33802. };
  33803. /**
  33804. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33805. * Please consider using the same method from the MeshBuilder class instead.
  33806. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33807. * 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`).
  33808. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33809. * 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.
  33810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33811. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33813. */
  33814. Mesh.CreateIcoSphere = function (name, options, scene) {
  33815. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33816. };
  33817. /**
  33818. * Creates a decal mesh.
  33819. * Please consider using the same method from the MeshBuilder class instead.
  33820. * 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.
  33821. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33822. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33823. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33824. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33825. */
  33826. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33827. var options = {
  33828. position: position,
  33829. normal: normal,
  33830. size: size,
  33831. angle: angle
  33832. };
  33833. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33834. };
  33835. // Skeletons
  33836. /**
  33837. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33838. */
  33839. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33840. if (!this._sourcePositions) {
  33841. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33842. if (!source) {
  33843. return this._sourcePositions;
  33844. }
  33845. this._sourcePositions = new Float32Array(source);
  33846. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33847. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33848. }
  33849. }
  33850. return this._sourcePositions;
  33851. };
  33852. /**
  33853. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33854. */
  33855. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33856. if (!this._sourceNormals) {
  33857. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33858. if (!source) {
  33859. return this._sourceNormals;
  33860. }
  33861. this._sourceNormals = new Float32Array(source);
  33862. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33863. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33864. }
  33865. }
  33866. return this._sourceNormals;
  33867. };
  33868. /**
  33869. * Updates the vertex buffer by applying transformation from the bones.
  33870. * Returns the Mesh.
  33871. *
  33872. * @param {skeleton} skeleton to apply
  33873. */
  33874. Mesh.prototype.applySkeleton = function (skeleton) {
  33875. if (!this.geometry) {
  33876. return this;
  33877. }
  33878. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33879. return this;
  33880. }
  33881. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33882. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33883. return this;
  33884. }
  33885. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33886. return this;
  33887. }
  33888. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33889. return this;
  33890. }
  33891. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33892. return this;
  33893. }
  33894. if (!this._sourcePositions) {
  33895. var submeshes = this.subMeshes.slice();
  33896. this.setPositionsForCPUSkinning();
  33897. this.subMeshes = submeshes;
  33898. }
  33899. if (!this._sourceNormals) {
  33900. this.setNormalsForCPUSkinning();
  33901. }
  33902. // positionsData checks for not being Float32Array will only pass at most once
  33903. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33904. if (!positionsData) {
  33905. return this;
  33906. }
  33907. if (!(positionsData instanceof Float32Array)) {
  33908. positionsData = new Float32Array(positionsData);
  33909. }
  33910. // normalsData checks for not being Float32Array will only pass at most once
  33911. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33912. if (!normalsData) {
  33913. return this;
  33914. }
  33915. if (!(normalsData instanceof Float32Array)) {
  33916. normalsData = new Float32Array(normalsData);
  33917. }
  33918. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33919. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33920. if (!matricesWeightsData || !matricesIndicesData) {
  33921. return this;
  33922. }
  33923. var needExtras = this.numBoneInfluencers > 4;
  33924. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33925. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33926. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33927. var tempVector3 = BABYLON.Vector3.Zero();
  33928. var finalMatrix = new BABYLON.Matrix();
  33929. var tempMatrix = new BABYLON.Matrix();
  33930. var matWeightIdx = 0;
  33931. var inf;
  33932. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33933. var weight;
  33934. for (inf = 0; inf < 4; inf++) {
  33935. weight = matricesWeightsData[matWeightIdx + inf];
  33936. if (weight > 0) {
  33937. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33938. finalMatrix.addToSelf(tempMatrix);
  33939. }
  33940. else
  33941. break;
  33942. }
  33943. if (needExtras) {
  33944. for (inf = 0; inf < 4; inf++) {
  33945. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33946. if (weight > 0) {
  33947. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33948. finalMatrix.addToSelf(tempMatrix);
  33949. }
  33950. else
  33951. break;
  33952. }
  33953. }
  33954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33955. tempVector3.toArray(positionsData, index);
  33956. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33957. tempVector3.toArray(normalsData, index);
  33958. finalMatrix.reset();
  33959. }
  33960. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33961. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33962. return this;
  33963. };
  33964. // Tools
  33965. /**
  33966. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33967. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33968. */
  33969. Mesh.MinMax = function (meshes) {
  33970. var minVector = null;
  33971. var maxVector = null;
  33972. meshes.forEach(function (mesh, index, array) {
  33973. var boundingInfo = mesh.getBoundingInfo();
  33974. var boundingBox = boundingInfo.boundingBox;
  33975. if (!minVector || !maxVector) {
  33976. minVector = boundingBox.minimumWorld;
  33977. maxVector = boundingBox.maximumWorld;
  33978. }
  33979. else {
  33980. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33981. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33982. }
  33983. });
  33984. if (!minVector || !maxVector) {
  33985. return {
  33986. min: BABYLON.Vector3.Zero(),
  33987. max: BABYLON.Vector3.Zero()
  33988. };
  33989. }
  33990. return {
  33991. min: minVector,
  33992. max: maxVector
  33993. };
  33994. };
  33995. /**
  33996. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33997. */
  33998. Mesh.Center = function (meshesOrMinMaxVector) {
  33999. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34000. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34001. };
  34002. /**
  34003. * Merge the array of meshes into a single mesh for performance reasons.
  34004. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34005. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34006. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34007. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34008. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34009. */
  34010. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34011. if (disposeSource === void 0) { disposeSource = true; }
  34012. var index;
  34013. if (!allow32BitsIndices) {
  34014. var totalVertices = 0;
  34015. // Counting vertices
  34016. for (index = 0; index < meshes.length; index++) {
  34017. if (meshes[index]) {
  34018. totalVertices += meshes[index].getTotalVertices();
  34019. if (totalVertices > 65536) {
  34020. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34021. return null;
  34022. }
  34023. }
  34024. }
  34025. }
  34026. // Merge
  34027. var vertexData = null;
  34028. var otherVertexData;
  34029. var indiceArray = new Array();
  34030. var source = null;
  34031. for (index = 0; index < meshes.length; index++) {
  34032. if (meshes[index]) {
  34033. meshes[index].computeWorldMatrix(true);
  34034. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34035. otherVertexData.transform(meshes[index].getWorldMatrix());
  34036. if (vertexData) {
  34037. vertexData.merge(otherVertexData);
  34038. }
  34039. else {
  34040. vertexData = otherVertexData;
  34041. source = meshes[index];
  34042. }
  34043. if (subdivideWithSubMeshes) {
  34044. indiceArray.push(meshes[index].getTotalIndices());
  34045. }
  34046. }
  34047. }
  34048. source = source;
  34049. if (!meshSubclass) {
  34050. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34051. }
  34052. vertexData.applyToMesh(meshSubclass);
  34053. // Setting properties
  34054. meshSubclass.material = source.material;
  34055. meshSubclass.checkCollisions = source.checkCollisions;
  34056. // Cleaning
  34057. if (disposeSource) {
  34058. for (index = 0; index < meshes.length; index++) {
  34059. if (meshes[index]) {
  34060. meshes[index].dispose();
  34061. }
  34062. }
  34063. }
  34064. // Subdivide
  34065. if (subdivideWithSubMeshes) {
  34066. //-- Suppresions du submesh global
  34067. meshSubclass.releaseSubMeshes();
  34068. index = 0;
  34069. var offset = 0;
  34070. //-- aplique la subdivision en fonction du tableau d'indices
  34071. while (index < indiceArray.length) {
  34072. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34073. offset += indiceArray[index];
  34074. index++;
  34075. }
  34076. }
  34077. return meshSubclass;
  34078. };
  34079. // Consts
  34080. Mesh._FRONTSIDE = 0;
  34081. Mesh._BACKSIDE = 1;
  34082. Mesh._DOUBLESIDE = 2;
  34083. Mesh._DEFAULTSIDE = 0;
  34084. Mesh._NO_CAP = 0;
  34085. Mesh._CAP_START = 1;
  34086. Mesh._CAP_END = 2;
  34087. Mesh._CAP_ALL = 3;
  34088. return Mesh;
  34089. }(BABYLON.AbstractMesh));
  34090. BABYLON.Mesh = Mesh;
  34091. })(BABYLON || (BABYLON = {}));
  34092. //# sourceMappingURL=babylon.mesh.js.map
  34093. var BABYLON;
  34094. (function (BABYLON) {
  34095. var BaseSubMesh = /** @class */ (function () {
  34096. function BaseSubMesh() {
  34097. }
  34098. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34099. get: function () {
  34100. return this._materialEffect;
  34101. },
  34102. enumerable: true,
  34103. configurable: true
  34104. });
  34105. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34106. if (defines === void 0) { defines = null; }
  34107. if (this._materialEffect === effect) {
  34108. if (!effect) {
  34109. this._materialDefines = null;
  34110. }
  34111. return;
  34112. }
  34113. this._materialDefines = defines;
  34114. this._materialEffect = effect;
  34115. };
  34116. return BaseSubMesh;
  34117. }());
  34118. BABYLON.BaseSubMesh = BaseSubMesh;
  34119. var SubMesh = /** @class */ (function (_super) {
  34120. __extends(SubMesh, _super);
  34121. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34122. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34123. var _this = _super.call(this) || this;
  34124. _this.materialIndex = materialIndex;
  34125. _this.verticesStart = verticesStart;
  34126. _this.verticesCount = verticesCount;
  34127. _this.indexStart = indexStart;
  34128. _this.indexCount = indexCount;
  34129. _this._renderId = 0;
  34130. _this._mesh = mesh;
  34131. _this._renderingMesh = renderingMesh || mesh;
  34132. mesh.subMeshes.push(_this);
  34133. _this._trianglePlanes = [];
  34134. _this._id = mesh.subMeshes.length - 1;
  34135. if (createBoundingBox) {
  34136. _this.refreshBoundingInfo();
  34137. mesh.computeWorldMatrix(true);
  34138. }
  34139. return _this;
  34140. }
  34141. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34142. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34143. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34144. };
  34145. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34146. get: function () {
  34147. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34148. },
  34149. enumerable: true,
  34150. configurable: true
  34151. });
  34152. /**
  34153. * Returns the submesh BoudingInfo object.
  34154. */
  34155. SubMesh.prototype.getBoundingInfo = function () {
  34156. if (this.IsGlobal) {
  34157. return this._mesh.getBoundingInfo();
  34158. }
  34159. return this._boundingInfo;
  34160. };
  34161. /**
  34162. * Sets the submesh BoundingInfo.
  34163. * Return the SubMesh.
  34164. */
  34165. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34166. this._boundingInfo = boundingInfo;
  34167. return this;
  34168. };
  34169. /**
  34170. * Returns the mesh of the current submesh.
  34171. */
  34172. SubMesh.prototype.getMesh = function () {
  34173. return this._mesh;
  34174. };
  34175. /**
  34176. * Returns the rendering mesh of the submesh.
  34177. */
  34178. SubMesh.prototype.getRenderingMesh = function () {
  34179. return this._renderingMesh;
  34180. };
  34181. /**
  34182. * Returns the submesh material.
  34183. */
  34184. SubMesh.prototype.getMaterial = function () {
  34185. var rootMaterial = this._renderingMesh.material;
  34186. if (rootMaterial === null || rootMaterial === undefined) {
  34187. return this._mesh.getScene().defaultMaterial;
  34188. }
  34189. else if (rootMaterial.getSubMaterial) {
  34190. var multiMaterial = rootMaterial;
  34191. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34192. if (this._currentMaterial !== effectiveMaterial) {
  34193. this._currentMaterial = effectiveMaterial;
  34194. this._materialDefines = null;
  34195. }
  34196. return effectiveMaterial;
  34197. }
  34198. return rootMaterial;
  34199. };
  34200. // Methods
  34201. /**
  34202. * Sets a new updated BoundingInfo object to the submesh.
  34203. * Returns the SubMesh.
  34204. */
  34205. SubMesh.prototype.refreshBoundingInfo = function () {
  34206. this._lastColliderWorldVertices = null;
  34207. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34208. return this;
  34209. }
  34210. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34211. if (!data) {
  34212. this._boundingInfo = this._mesh.getBoundingInfo();
  34213. return this;
  34214. }
  34215. var indices = this._renderingMesh.getIndices();
  34216. var extend;
  34217. //is this the only submesh?
  34218. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34219. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34220. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34221. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34222. }
  34223. else {
  34224. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34225. }
  34226. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34227. return this;
  34228. };
  34229. SubMesh.prototype._checkCollision = function (collider) {
  34230. var boundingInfo = this.getBoundingInfo();
  34231. return boundingInfo._checkCollision(collider);
  34232. };
  34233. /**
  34234. * Updates the submesh BoundingInfo.
  34235. * Returns the Submesh.
  34236. */
  34237. SubMesh.prototype.updateBoundingInfo = function (world) {
  34238. var boundingInfo = this.getBoundingInfo();
  34239. if (!boundingInfo) {
  34240. this.refreshBoundingInfo();
  34241. boundingInfo = this.getBoundingInfo();
  34242. }
  34243. boundingInfo.update(world);
  34244. return this;
  34245. };
  34246. /**
  34247. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34248. * Boolean returned.
  34249. */
  34250. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34251. var boundingInfo = this.getBoundingInfo();
  34252. if (!boundingInfo) {
  34253. return false;
  34254. }
  34255. return boundingInfo.isInFrustum(frustumPlanes);
  34256. };
  34257. /**
  34258. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34259. * Boolean returned.
  34260. */
  34261. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34262. var boundingInfo = this.getBoundingInfo();
  34263. if (!boundingInfo) {
  34264. return false;
  34265. }
  34266. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34267. };
  34268. /**
  34269. * Renders the submesh.
  34270. * Returns it.
  34271. */
  34272. SubMesh.prototype.render = function (enableAlphaMode) {
  34273. this._renderingMesh.render(this, enableAlphaMode);
  34274. return this;
  34275. };
  34276. /**
  34277. * Returns a new Index Buffer.
  34278. * Type returned : WebGLBuffer.
  34279. */
  34280. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34281. if (!this._linesIndexBuffer) {
  34282. var linesIndices = [];
  34283. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34284. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34285. }
  34286. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34287. this.linesIndexCount = linesIndices.length;
  34288. }
  34289. return this._linesIndexBuffer;
  34290. };
  34291. /**
  34292. * True is the passed Ray intersects the submesh bounding box.
  34293. * Boolean returned.
  34294. */
  34295. SubMesh.prototype.canIntersects = function (ray) {
  34296. var boundingInfo = this.getBoundingInfo();
  34297. if (!boundingInfo) {
  34298. return false;
  34299. }
  34300. return ray.intersectsBox(boundingInfo.boundingBox);
  34301. };
  34302. /**
  34303. * Returns an object IntersectionInfo.
  34304. */
  34305. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34306. var intersectInfo = null;
  34307. var material = this.getMaterial();
  34308. if (!material) {
  34309. return null;
  34310. }
  34311. switch (material.fillMode) {
  34312. case BABYLON.Material.PointListDrawMode:
  34313. case BABYLON.Material.LineListDrawMode:
  34314. case BABYLON.Material.LineLoopDrawMode:
  34315. case BABYLON.Material.LineStripDrawMode:
  34316. case BABYLON.Material.TriangleFanDrawMode:
  34317. case BABYLON.Material.TriangleStripDrawMode:
  34318. return null;
  34319. }
  34320. // LineMesh first as it's also a Mesh...
  34321. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34322. var lineMesh = this._mesh;
  34323. // Line test
  34324. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34325. var p0 = positions[indices[index]];
  34326. var p1 = positions[indices[index + 1]];
  34327. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34328. if (length < 0) {
  34329. continue;
  34330. }
  34331. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34332. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34333. if (fastCheck) {
  34334. break;
  34335. }
  34336. }
  34337. }
  34338. }
  34339. else {
  34340. // Triangles test
  34341. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34342. var p0 = positions[indices[index]];
  34343. var p1 = positions[indices[index + 1]];
  34344. var p2 = positions[indices[index + 2]];
  34345. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34346. if (currentIntersectInfo) {
  34347. if (currentIntersectInfo.distance < 0) {
  34348. continue;
  34349. }
  34350. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34351. intersectInfo = currentIntersectInfo;
  34352. intersectInfo.faceId = index / 3;
  34353. if (fastCheck) {
  34354. break;
  34355. }
  34356. }
  34357. }
  34358. }
  34359. }
  34360. return intersectInfo;
  34361. };
  34362. SubMesh.prototype._rebuild = function () {
  34363. if (this._linesIndexBuffer) {
  34364. this._linesIndexBuffer = null;
  34365. }
  34366. };
  34367. // Clone
  34368. /**
  34369. * Creates a new Submesh from the passed Mesh.
  34370. */
  34371. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34372. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34373. if (!this.IsGlobal) {
  34374. var boundingInfo = this.getBoundingInfo();
  34375. if (!boundingInfo) {
  34376. return result;
  34377. }
  34378. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34379. }
  34380. return result;
  34381. };
  34382. // Dispose
  34383. /**
  34384. * Disposes the Submesh.
  34385. * Returns nothing.
  34386. */
  34387. SubMesh.prototype.dispose = function () {
  34388. if (this._linesIndexBuffer) {
  34389. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34390. this._linesIndexBuffer = null;
  34391. }
  34392. // Remove from mesh
  34393. var index = this._mesh.subMeshes.indexOf(this);
  34394. this._mesh.subMeshes.splice(index, 1);
  34395. };
  34396. // Statics
  34397. /**
  34398. * Creates a new Submesh from the passed parameters :
  34399. * - materialIndex (integer) : the index of the main mesh material.
  34400. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34401. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34402. * - mesh (Mesh) : the main mesh to create the submesh from.
  34403. * - renderingMesh (optional Mesh) : rendering mesh.
  34404. */
  34405. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34406. var minVertexIndex = Number.MAX_VALUE;
  34407. var maxVertexIndex = -Number.MAX_VALUE;
  34408. renderingMesh = (renderingMesh || mesh);
  34409. var indices = renderingMesh.getIndices();
  34410. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34411. var vertexIndex = indices[index];
  34412. if (vertexIndex < minVertexIndex)
  34413. minVertexIndex = vertexIndex;
  34414. if (vertexIndex > maxVertexIndex)
  34415. maxVertexIndex = vertexIndex;
  34416. }
  34417. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34418. };
  34419. return SubMesh;
  34420. }(BaseSubMesh));
  34421. BABYLON.SubMesh = SubMesh;
  34422. })(BABYLON || (BABYLON = {}));
  34423. //# sourceMappingURL=babylon.subMesh.js.map
  34424. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34425. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34426. s = arguments[i];
  34427. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34428. t[p] = s[p];
  34429. }
  34430. return t;
  34431. };
  34432. var BABYLON;
  34433. (function (BABYLON) {
  34434. /**
  34435. * Manages the defines for the Material
  34436. */
  34437. var MaterialDefines = /** @class */ (function () {
  34438. function MaterialDefines() {
  34439. this._isDirty = true;
  34440. /** @hidden */
  34441. this._areLightsDirty = true;
  34442. /** @hidden */
  34443. this._areAttributesDirty = true;
  34444. /** @hidden */
  34445. this._areTexturesDirty = true;
  34446. /** @hidden */
  34447. this._areFresnelDirty = true;
  34448. /** @hidden */
  34449. this._areMiscDirty = true;
  34450. /** @hidden */
  34451. this._areImageProcessingDirty = true;
  34452. /** @hidden */
  34453. this._normals = false;
  34454. /** @hidden */
  34455. this._uvs = false;
  34456. /** @hidden */
  34457. this._needNormals = false;
  34458. /** @hidden */
  34459. this._needUVs = false;
  34460. }
  34461. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34462. /**
  34463. * Specifies if the material needs to be re-calculated
  34464. */
  34465. get: function () {
  34466. return this._isDirty;
  34467. },
  34468. enumerable: true,
  34469. configurable: true
  34470. });
  34471. /**
  34472. * Marks the material to indicate that it has been re-calculated
  34473. */
  34474. MaterialDefines.prototype.markAsProcessed = function () {
  34475. this._isDirty = false;
  34476. this._areAttributesDirty = false;
  34477. this._areTexturesDirty = false;
  34478. this._areFresnelDirty = false;
  34479. this._areLightsDirty = false;
  34480. this._areMiscDirty = false;
  34481. this._areImageProcessingDirty = false;
  34482. };
  34483. /**
  34484. * Marks the material to indicate that it needs to be re-calculated
  34485. */
  34486. MaterialDefines.prototype.markAsUnprocessed = function () {
  34487. this._isDirty = true;
  34488. };
  34489. /**
  34490. * Marks the material to indicate all of its defines need to be re-calculated
  34491. */
  34492. MaterialDefines.prototype.markAllAsDirty = function () {
  34493. this._areTexturesDirty = true;
  34494. this._areAttributesDirty = true;
  34495. this._areLightsDirty = true;
  34496. this._areFresnelDirty = true;
  34497. this._areMiscDirty = true;
  34498. this._areImageProcessingDirty = true;
  34499. this._isDirty = true;
  34500. };
  34501. /**
  34502. * Marks the material to indicate that image processing needs to be re-calculated
  34503. */
  34504. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34505. this._areImageProcessingDirty = true;
  34506. this._isDirty = true;
  34507. };
  34508. /**
  34509. * Marks the material to indicate the lights need to be re-calculated
  34510. */
  34511. MaterialDefines.prototype.markAsLightDirty = function () {
  34512. this._areLightsDirty = true;
  34513. this._isDirty = true;
  34514. };
  34515. /**
  34516. * Marks the attribute state as changed
  34517. */
  34518. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34519. this._areAttributesDirty = true;
  34520. this._isDirty = true;
  34521. };
  34522. /**
  34523. * Marks the texture state as changed
  34524. */
  34525. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34526. this._areTexturesDirty = true;
  34527. this._isDirty = true;
  34528. };
  34529. /**
  34530. * Marks the fresnel state as changed
  34531. */
  34532. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34533. this._areFresnelDirty = true;
  34534. this._isDirty = true;
  34535. };
  34536. /**
  34537. * Marks the misc state as changed
  34538. */
  34539. MaterialDefines.prototype.markAsMiscDirty = function () {
  34540. this._areMiscDirty = true;
  34541. this._isDirty = true;
  34542. };
  34543. /**
  34544. * Rebuilds the material defines
  34545. */
  34546. MaterialDefines.prototype.rebuild = function () {
  34547. if (this._keys) {
  34548. delete this._keys;
  34549. }
  34550. this._keys = [];
  34551. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34552. var key = _a[_i];
  34553. if (key[0] === "_") {
  34554. continue;
  34555. }
  34556. this._keys.push(key);
  34557. }
  34558. };
  34559. /**
  34560. * Specifies if two material defines are equal
  34561. * @param other - A material define instance to compare to
  34562. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34563. */
  34564. MaterialDefines.prototype.isEqual = function (other) {
  34565. if (this._keys.length !== other._keys.length) {
  34566. return false;
  34567. }
  34568. for (var index = 0; index < this._keys.length; index++) {
  34569. var prop = this._keys[index];
  34570. if (this[prop] !== other[prop]) {
  34571. return false;
  34572. }
  34573. }
  34574. return true;
  34575. };
  34576. /**
  34577. * Clones this instance's defines to another instance
  34578. * @param other - material defines to clone values to
  34579. */
  34580. MaterialDefines.prototype.cloneTo = function (other) {
  34581. if (this._keys.length !== other._keys.length) {
  34582. other._keys = this._keys.slice(0);
  34583. }
  34584. for (var index = 0; index < this._keys.length; index++) {
  34585. var prop = this._keys[index];
  34586. other[prop] = this[prop];
  34587. }
  34588. };
  34589. /**
  34590. * Resets the material define values
  34591. */
  34592. MaterialDefines.prototype.reset = function () {
  34593. for (var index = 0; index < this._keys.length; index++) {
  34594. var prop = this._keys[index];
  34595. var type = typeof this[prop];
  34596. switch (type) {
  34597. case "number":
  34598. this[prop] = 0;
  34599. break;
  34600. case "string":
  34601. this[prop] = "";
  34602. break;
  34603. default:
  34604. this[prop] = false;
  34605. break;
  34606. }
  34607. }
  34608. };
  34609. /**
  34610. * Converts the material define values to a string
  34611. * @returns - String of material define information
  34612. */
  34613. MaterialDefines.prototype.toString = function () {
  34614. var result = "";
  34615. for (var index = 0; index < this._keys.length; index++) {
  34616. var prop = this._keys[index];
  34617. var value = this[prop];
  34618. var type = typeof value;
  34619. switch (type) {
  34620. case "number":
  34621. case "string":
  34622. result += "#define " + prop + " " + value + "\n";
  34623. break;
  34624. default:
  34625. if (value) {
  34626. result += "#define " + prop + "\n";
  34627. }
  34628. break;
  34629. }
  34630. }
  34631. return result;
  34632. };
  34633. return MaterialDefines;
  34634. }());
  34635. BABYLON.MaterialDefines = MaterialDefines;
  34636. /**
  34637. * Base class for the main features of a material in Babylon.js
  34638. */
  34639. var Material = /** @class */ (function () {
  34640. /**
  34641. * Creates a material instance
  34642. * @param name defines the name of the material
  34643. * @param scene defines the scene to reference
  34644. * @param doNotAdd specifies if the material should be added to the scene
  34645. */
  34646. function Material(name, scene, doNotAdd) {
  34647. /**
  34648. * Specifies if the ready state should be checked on each call
  34649. */
  34650. this.checkReadyOnEveryCall = false;
  34651. /**
  34652. * Specifies if the ready state should be checked once
  34653. */
  34654. this.checkReadyOnlyOnce = false;
  34655. /**
  34656. * The state of the material
  34657. */
  34658. this.state = "";
  34659. /**
  34660. * The alpha value of the material
  34661. */
  34662. this._alpha = 1.0;
  34663. /**
  34664. * Specifies if back face culling is enabled
  34665. */
  34666. this._backFaceCulling = true;
  34667. /**
  34668. * Specifies if the material should be serialized
  34669. */
  34670. this.doNotSerialize = false;
  34671. /**
  34672. * Specifies if the effect should be stored on sub meshes
  34673. */
  34674. this.storeEffectOnSubMeshes = false;
  34675. /**
  34676. * An event triggered when the material is disposed
  34677. */
  34678. this.onDisposeObservable = new BABYLON.Observable();
  34679. /**
  34680. * An event triggered when the material is bound
  34681. */
  34682. this.onBindObservable = new BABYLON.Observable();
  34683. /**
  34684. * An event triggered when the material is unbound
  34685. */
  34686. this.onUnBindObservable = new BABYLON.Observable();
  34687. /**
  34688. * Stores the value of the alpha mode
  34689. */
  34690. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34691. /**
  34692. * Stores the state of the need depth pre-pass value
  34693. */
  34694. this._needDepthPrePass = false;
  34695. /**
  34696. * Specifies if depth writing should be disabled
  34697. */
  34698. this.disableDepthWrite = false;
  34699. /**
  34700. * Specifies if depth writing should be forced
  34701. */
  34702. this.forceDepthWrite = false;
  34703. /**
  34704. * Specifies if there should be a separate pass for culling
  34705. */
  34706. this.separateCullingPass = false;
  34707. /**
  34708. * Stores the state specifing if fog should be enabled
  34709. */
  34710. this._fogEnabled = true;
  34711. /**
  34712. * Stores the size of points
  34713. */
  34714. this.pointSize = 1.0;
  34715. /**
  34716. * Stores the z offset value
  34717. */
  34718. this.zOffset = 0;
  34719. /**
  34720. * Specifies if the material was previously ready
  34721. */
  34722. this._wasPreviouslyReady = false;
  34723. /**
  34724. * Stores the fill mode state
  34725. */
  34726. this._fillMode = Material.TriangleFillMode;
  34727. this.name = name;
  34728. this.id = name || BABYLON.Tools.RandomId();
  34729. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34730. if (this._scene.useRightHandedSystem) {
  34731. this.sideOrientation = Material.ClockWiseSideOrientation;
  34732. }
  34733. else {
  34734. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34735. }
  34736. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34737. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34738. if (!doNotAdd) {
  34739. this._scene.materials.push(this);
  34740. }
  34741. }
  34742. Object.defineProperty(Material, "TriangleFillMode", {
  34743. /**
  34744. * Returns the triangle fill mode
  34745. */
  34746. get: function () {
  34747. return Material._TriangleFillMode;
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. Object.defineProperty(Material, "WireFrameFillMode", {
  34753. /**
  34754. * Returns the wireframe mode
  34755. */
  34756. get: function () {
  34757. return Material._WireFrameFillMode;
  34758. },
  34759. enumerable: true,
  34760. configurable: true
  34761. });
  34762. Object.defineProperty(Material, "PointFillMode", {
  34763. /**
  34764. * Returns the point fill mode
  34765. */
  34766. get: function () {
  34767. return Material._PointFillMode;
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material, "PointListDrawMode", {
  34773. /**
  34774. * Returns the point list draw mode
  34775. */
  34776. get: function () {
  34777. return Material._PointListDrawMode;
  34778. },
  34779. enumerable: true,
  34780. configurable: true
  34781. });
  34782. Object.defineProperty(Material, "LineListDrawMode", {
  34783. /**
  34784. * Returns the line list draw mode
  34785. */
  34786. get: function () {
  34787. return Material._LineListDrawMode;
  34788. },
  34789. enumerable: true,
  34790. configurable: true
  34791. });
  34792. Object.defineProperty(Material, "LineLoopDrawMode", {
  34793. /**
  34794. * Returns the line loop draw mode
  34795. */
  34796. get: function () {
  34797. return Material._LineLoopDrawMode;
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(Material, "LineStripDrawMode", {
  34803. /**
  34804. * Returns the line strip draw mode
  34805. */
  34806. get: function () {
  34807. return Material._LineStripDrawMode;
  34808. },
  34809. enumerable: true,
  34810. configurable: true
  34811. });
  34812. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34813. /**
  34814. * Returns the triangle strip draw mode
  34815. */
  34816. get: function () {
  34817. return Material._TriangleStripDrawMode;
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34823. /**
  34824. * Returns the triangle fan draw mode
  34825. */
  34826. get: function () {
  34827. return Material._TriangleFanDrawMode;
  34828. },
  34829. enumerable: true,
  34830. configurable: true
  34831. });
  34832. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34833. /**
  34834. * Returns the clock-wise side orientation
  34835. */
  34836. get: function () {
  34837. return Material._ClockWiseSideOrientation;
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34843. /**
  34844. * Returns the counter clock-wise side orientation
  34845. */
  34846. get: function () {
  34847. return Material._CounterClockWiseSideOrientation;
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. Object.defineProperty(Material, "TextureDirtyFlag", {
  34853. /**
  34854. * Returns the dirty texture flag value
  34855. */
  34856. get: function () {
  34857. return Material._TextureDirtyFlag;
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(Material, "LightDirtyFlag", {
  34863. /**
  34864. * Returns the dirty light flag value
  34865. */
  34866. get: function () {
  34867. return Material._LightDirtyFlag;
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34873. /**
  34874. * Returns the dirty fresnel flag value
  34875. */
  34876. get: function () {
  34877. return Material._FresnelDirtyFlag;
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34883. /**
  34884. * Returns the dirty attributes flag value
  34885. */
  34886. get: function () {
  34887. return Material._AttributesDirtyFlag;
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(Material, "MiscDirtyFlag", {
  34893. /**
  34894. * Returns the dirty misc flag value
  34895. */
  34896. get: function () {
  34897. return Material._MiscDirtyFlag;
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(Material.prototype, "alpha", {
  34903. /**
  34904. * Gets the alpha value of the material
  34905. */
  34906. get: function () {
  34907. return this._alpha;
  34908. },
  34909. /**
  34910. * Sets the alpha value of the material
  34911. */
  34912. set: function (value) {
  34913. if (this._alpha === value) {
  34914. return;
  34915. }
  34916. this._alpha = value;
  34917. this.markAsDirty(Material.MiscDirtyFlag);
  34918. },
  34919. enumerable: true,
  34920. configurable: true
  34921. });
  34922. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34923. /**
  34924. * Gets the back-face culling state
  34925. */
  34926. get: function () {
  34927. return this._backFaceCulling;
  34928. },
  34929. /**
  34930. * Sets the back-face culling state
  34931. */
  34932. set: function (value) {
  34933. if (this._backFaceCulling === value) {
  34934. return;
  34935. }
  34936. this._backFaceCulling = value;
  34937. this.markAsDirty(Material.TextureDirtyFlag);
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(Material.prototype, "onDispose", {
  34943. /**
  34944. * Called during a dispose event
  34945. */
  34946. set: function (callback) {
  34947. if (this._onDisposeObserver) {
  34948. this.onDisposeObservable.remove(this._onDisposeObserver);
  34949. }
  34950. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34951. },
  34952. enumerable: true,
  34953. configurable: true
  34954. });
  34955. Object.defineProperty(Material.prototype, "onBind", {
  34956. /**
  34957. * Called during a bind event
  34958. */
  34959. set: function (callback) {
  34960. if (this._onBindObserver) {
  34961. this.onBindObservable.remove(this._onBindObserver);
  34962. }
  34963. this._onBindObserver = this.onBindObservable.add(callback);
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. Object.defineProperty(Material.prototype, "alphaMode", {
  34969. /**
  34970. * Gets the value of the alpha mode
  34971. */
  34972. get: function () {
  34973. return this._alphaMode;
  34974. },
  34975. /**
  34976. * Sets the value of the alpha mode.
  34977. *
  34978. * | Value | Type | Description |
  34979. * | --- | --- | --- |
  34980. * | 0 | ALPHA_DISABLE | |
  34981. * | 1 | ALPHA_ADD | |
  34982. * | 2 | ALPHA_COMBINE | |
  34983. * | 3 | ALPHA_SUBTRACT | |
  34984. * | 4 | ALPHA_MULTIPLY | |
  34985. * | 5 | ALPHA_MAXIMIZED | |
  34986. * | 6 | ALPHA_ONEONE | |
  34987. * | 7 | ALPHA_PREMULTIPLIED | |
  34988. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34989. * | 9 | ALPHA_INTERPOLATE | |
  34990. * | 10 | ALPHA_SCREENMODE | |
  34991. *
  34992. */
  34993. set: function (value) {
  34994. if (this._alphaMode === value) {
  34995. return;
  34996. }
  34997. this._alphaMode = value;
  34998. this.markAsDirty(Material.TextureDirtyFlag);
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35004. /**
  35005. * Gets the depth pre-pass value
  35006. */
  35007. get: function () {
  35008. return this._needDepthPrePass;
  35009. },
  35010. /**
  35011. * Sets the need depth pre-pass value
  35012. */
  35013. set: function (value) {
  35014. if (this._needDepthPrePass === value) {
  35015. return;
  35016. }
  35017. this._needDepthPrePass = value;
  35018. if (this._needDepthPrePass) {
  35019. this.checkReadyOnEveryCall = true;
  35020. }
  35021. },
  35022. enumerable: true,
  35023. configurable: true
  35024. });
  35025. Object.defineProperty(Material.prototype, "fogEnabled", {
  35026. /**
  35027. * Gets the value of the fog enabled state
  35028. */
  35029. get: function () {
  35030. return this._fogEnabled;
  35031. },
  35032. /**
  35033. * Sets the state for enabling fog
  35034. */
  35035. set: function (value) {
  35036. if (this._fogEnabled === value) {
  35037. return;
  35038. }
  35039. this._fogEnabled = value;
  35040. this.markAsDirty(Material.MiscDirtyFlag);
  35041. },
  35042. enumerable: true,
  35043. configurable: true
  35044. });
  35045. Object.defineProperty(Material.prototype, "wireframe", {
  35046. /**
  35047. * Gets a value specifying if wireframe mode is enabled
  35048. */
  35049. get: function () {
  35050. switch (this._fillMode) {
  35051. case Material.WireFrameFillMode:
  35052. case Material.LineListDrawMode:
  35053. case Material.LineLoopDrawMode:
  35054. case Material.LineStripDrawMode:
  35055. return true;
  35056. }
  35057. return this._scene.forceWireframe;
  35058. },
  35059. /**
  35060. * Sets the state of wireframe mode
  35061. */
  35062. set: function (value) {
  35063. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35064. },
  35065. enumerable: true,
  35066. configurable: true
  35067. });
  35068. Object.defineProperty(Material.prototype, "pointsCloud", {
  35069. /**
  35070. * Gets the value specifying if point clouds are enabled
  35071. */
  35072. get: function () {
  35073. switch (this._fillMode) {
  35074. case Material.PointFillMode:
  35075. case Material.PointListDrawMode:
  35076. return true;
  35077. }
  35078. return this._scene.forcePointsCloud;
  35079. },
  35080. /**
  35081. * Sets the state of point cloud mode
  35082. */
  35083. set: function (value) {
  35084. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(Material.prototype, "fillMode", {
  35090. /**
  35091. * Gets the material fill mode
  35092. */
  35093. get: function () {
  35094. return this._fillMode;
  35095. },
  35096. /**
  35097. * Sets the material fill mode
  35098. */
  35099. set: function (value) {
  35100. if (this._fillMode === value) {
  35101. return;
  35102. }
  35103. this._fillMode = value;
  35104. this.markAsDirty(Material.MiscDirtyFlag);
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. /**
  35110. * Returns a string representation of the current material
  35111. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35112. * @returns a string with material information
  35113. */
  35114. Material.prototype.toString = function (fullDetails) {
  35115. var ret = "Name: " + this.name;
  35116. if (fullDetails) {
  35117. }
  35118. return ret;
  35119. };
  35120. /**
  35121. * Gets the class name of the material
  35122. * @returns a string with the class name of the material
  35123. */
  35124. Material.prototype.getClassName = function () {
  35125. return "Material";
  35126. };
  35127. Object.defineProperty(Material.prototype, "isFrozen", {
  35128. /**
  35129. * Specifies if updates for the material been locked
  35130. */
  35131. get: function () {
  35132. return this.checkReadyOnlyOnce;
  35133. },
  35134. enumerable: true,
  35135. configurable: true
  35136. });
  35137. /**
  35138. * Locks updates for the material
  35139. */
  35140. Material.prototype.freeze = function () {
  35141. this.checkReadyOnlyOnce = true;
  35142. };
  35143. /**
  35144. * Unlocks updates for the material
  35145. */
  35146. Material.prototype.unfreeze = function () {
  35147. this.checkReadyOnlyOnce = false;
  35148. };
  35149. /**
  35150. * Specifies if the material is ready to be used
  35151. * @param mesh defines the mesh to check
  35152. * @param useInstances specifies if instances should be used
  35153. * @returns a boolean indicating if the material is ready to be used
  35154. */
  35155. Material.prototype.isReady = function (mesh, useInstances) {
  35156. return true;
  35157. };
  35158. /**
  35159. * Specifies that the submesh is ready to be used
  35160. * @param mesh defines the mesh to check
  35161. * @param subMesh defines which submesh to check
  35162. * @param useInstances specifies that instances should be used
  35163. * @returns a boolean indicating that the submesh is ready or not
  35164. */
  35165. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35166. return false;
  35167. };
  35168. /**
  35169. * Returns the material effect
  35170. * @returns the effect associated with the material
  35171. */
  35172. Material.prototype.getEffect = function () {
  35173. return this._effect;
  35174. };
  35175. /**
  35176. * Returns the current scene
  35177. * @returns a Scene
  35178. */
  35179. Material.prototype.getScene = function () {
  35180. return this._scene;
  35181. };
  35182. /**
  35183. * Specifies if the material will require alpha blending
  35184. * @returns a boolean specifying if alpha blending is needed
  35185. */
  35186. Material.prototype.needAlphaBlending = function () {
  35187. return (this.alpha < 1.0);
  35188. };
  35189. /**
  35190. * Specifies if the mesh will require alpha blending
  35191. * @param mesh defines the mesh to check
  35192. * @returns a boolean specifying if alpha blending is needed for the mesh
  35193. */
  35194. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35195. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35196. };
  35197. /**
  35198. * Specifies if this material should be rendered in alpha test mode
  35199. * @returns a boolean specifying if an alpha test is needed.
  35200. */
  35201. Material.prototype.needAlphaTesting = function () {
  35202. return false;
  35203. };
  35204. /**
  35205. * Gets the texture used for the alpha test
  35206. * @returns the texture to use for alpha testing
  35207. */
  35208. Material.prototype.getAlphaTestTexture = function () {
  35209. return null;
  35210. };
  35211. /**
  35212. * Marks the material to indicate that it needs to be re-calculated
  35213. */
  35214. Material.prototype.markDirty = function () {
  35215. this._wasPreviouslyReady = false;
  35216. };
  35217. /** @hidden */
  35218. Material.prototype._preBind = function (effect, overrideOrientation) {
  35219. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35220. var engine = this._scene.getEngine();
  35221. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35222. var reverse = orientation === Material.ClockWiseSideOrientation;
  35223. engine.enableEffect(effect ? effect : this._effect);
  35224. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35225. return reverse;
  35226. };
  35227. /**
  35228. * Binds the material to the mesh
  35229. * @param world defines the world transformation matrix
  35230. * @param mesh defines the mesh to bind the material to
  35231. */
  35232. Material.prototype.bind = function (world, mesh) {
  35233. };
  35234. /**
  35235. * Binds the submesh to the material
  35236. * @param world defines the world transformation matrix
  35237. * @param mesh defines the mesh containing the submesh
  35238. * @param subMesh defines the submesh to bind the material to
  35239. */
  35240. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35241. };
  35242. /**
  35243. * Binds the world matrix to the material
  35244. * @param world defines the world transformation matrix
  35245. */
  35246. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35247. };
  35248. /**
  35249. * Binds the scene's uniform buffer to the effect.
  35250. * @param effect defines the effect to bind to the scene uniform buffer
  35251. * @param sceneUbo defines the uniform buffer storing scene data
  35252. */
  35253. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35254. sceneUbo.bindToEffect(effect, "Scene");
  35255. };
  35256. /**
  35257. * Binds the view matrix to the effect
  35258. * @param effect defines the effect to bind the view matrix to
  35259. */
  35260. Material.prototype.bindView = function (effect) {
  35261. if (!this._useUBO) {
  35262. effect.setMatrix("view", this.getScene().getViewMatrix());
  35263. }
  35264. else {
  35265. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35266. }
  35267. };
  35268. /**
  35269. * Binds the view projection matrix to the effect
  35270. * @param effect defines the effect to bind the view projection matrix to
  35271. */
  35272. Material.prototype.bindViewProjection = function (effect) {
  35273. if (!this._useUBO) {
  35274. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35275. }
  35276. else {
  35277. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35278. }
  35279. };
  35280. /**
  35281. * Specifies if material alpha testing should be turned on for the mesh
  35282. * @param mesh defines the mesh to check
  35283. */
  35284. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35285. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35286. };
  35287. /**
  35288. * Processes to execute after binding the material to a mesh
  35289. * @param mesh defines the rendered mesh
  35290. */
  35291. Material.prototype._afterBind = function (mesh) {
  35292. this._scene._cachedMaterial = this;
  35293. if (mesh) {
  35294. this._scene._cachedVisibility = mesh.visibility;
  35295. }
  35296. else {
  35297. this._scene._cachedVisibility = 1;
  35298. }
  35299. if (mesh) {
  35300. this.onBindObservable.notifyObservers(mesh);
  35301. }
  35302. if (this.disableDepthWrite) {
  35303. var engine = this._scene.getEngine();
  35304. this._cachedDepthWriteState = engine.getDepthWrite();
  35305. engine.setDepthWrite(false);
  35306. }
  35307. };
  35308. /**
  35309. * Unbinds the material from the mesh
  35310. */
  35311. Material.prototype.unbind = function () {
  35312. this.onUnBindObservable.notifyObservers(this);
  35313. if (this.disableDepthWrite) {
  35314. var engine = this._scene.getEngine();
  35315. engine.setDepthWrite(this._cachedDepthWriteState);
  35316. }
  35317. };
  35318. /**
  35319. * Gets the active textures from the material
  35320. * @returns an array of textures
  35321. */
  35322. Material.prototype.getActiveTextures = function () {
  35323. return [];
  35324. };
  35325. /**
  35326. * Specifies if the material uses a texture
  35327. * @param texture defines the texture to check against the material
  35328. * @returns a boolean specifying if the material uses the texture
  35329. */
  35330. Material.prototype.hasTexture = function (texture) {
  35331. return false;
  35332. };
  35333. /**
  35334. * Makes a duplicate of the material, and gives it a new name
  35335. * @param name defines the new name for the duplicated material
  35336. * @returns the cloned material
  35337. */
  35338. Material.prototype.clone = function (name) {
  35339. return null;
  35340. };
  35341. /**
  35342. * Gets the meshes bound to the material
  35343. * @returns an array of meshes bound to the material
  35344. */
  35345. Material.prototype.getBindedMeshes = function () {
  35346. var result = new Array();
  35347. for (var index = 0; index < this._scene.meshes.length; index++) {
  35348. var mesh = this._scene.meshes[index];
  35349. if (mesh.material === this) {
  35350. result.push(mesh);
  35351. }
  35352. }
  35353. return result;
  35354. };
  35355. /**
  35356. * Force shader compilation
  35357. * @param mesh defines the mesh associated with this material
  35358. * @param onCompiled defines a function to execute once the material is compiled
  35359. * @param options defines the options to configure the compilation
  35360. */
  35361. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35362. var _this = this;
  35363. var localOptions = __assign({ clipPlane: false }, options);
  35364. var subMesh = new BABYLON.BaseSubMesh();
  35365. var scene = this.getScene();
  35366. var checkReady = function () {
  35367. if (!_this._scene || !_this._scene.getEngine()) {
  35368. return;
  35369. }
  35370. if (subMesh._materialDefines) {
  35371. subMesh._materialDefines._renderId = -1;
  35372. }
  35373. var clipPlaneState = scene.clipPlane;
  35374. if (localOptions.clipPlane) {
  35375. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35376. }
  35377. if (_this.storeEffectOnSubMeshes) {
  35378. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35379. if (onCompiled) {
  35380. onCompiled(_this);
  35381. }
  35382. }
  35383. else {
  35384. setTimeout(checkReady, 16);
  35385. }
  35386. }
  35387. else {
  35388. if (_this.isReady(mesh)) {
  35389. if (onCompiled) {
  35390. onCompiled(_this);
  35391. }
  35392. }
  35393. else {
  35394. setTimeout(checkReady, 16);
  35395. }
  35396. }
  35397. if (localOptions.clipPlane) {
  35398. scene.clipPlane = clipPlaneState;
  35399. }
  35400. };
  35401. checkReady();
  35402. };
  35403. /**
  35404. * Force shader compilation
  35405. * @param mesh defines the mesh that will use this material
  35406. * @param options defines additional options for compiling the shaders
  35407. * @returns a promise that resolves when the compilation completes
  35408. */
  35409. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35410. var _this = this;
  35411. return new Promise(function (resolve) {
  35412. _this.forceCompilation(mesh, function () {
  35413. resolve();
  35414. }, options);
  35415. });
  35416. };
  35417. /**
  35418. * Marks a define in the material to indicate that it needs to be re-computed
  35419. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35420. */
  35421. Material.prototype.markAsDirty = function (flag) {
  35422. if (flag & Material.TextureDirtyFlag) {
  35423. this._markAllSubMeshesAsTexturesDirty();
  35424. }
  35425. if (flag & Material.LightDirtyFlag) {
  35426. this._markAllSubMeshesAsLightsDirty();
  35427. }
  35428. if (flag & Material.FresnelDirtyFlag) {
  35429. this._markAllSubMeshesAsFresnelDirty();
  35430. }
  35431. if (flag & Material.AttributesDirtyFlag) {
  35432. this._markAllSubMeshesAsAttributesDirty();
  35433. }
  35434. if (flag & Material.MiscDirtyFlag) {
  35435. this._markAllSubMeshesAsMiscDirty();
  35436. }
  35437. this.getScene().resetCachedMaterial();
  35438. };
  35439. /**
  35440. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35441. * @param func defines a function which checks material defines against the submeshes
  35442. */
  35443. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35444. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35445. var mesh = _a[_i];
  35446. if (!mesh.subMeshes) {
  35447. continue;
  35448. }
  35449. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35450. var subMesh = _c[_b];
  35451. if (subMesh.getMaterial() !== this) {
  35452. continue;
  35453. }
  35454. if (!subMesh._materialDefines) {
  35455. continue;
  35456. }
  35457. func(subMesh._materialDefines);
  35458. }
  35459. }
  35460. };
  35461. /**
  35462. * Indicates that image processing needs to be re-calculated for all submeshes
  35463. */
  35464. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35465. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35466. };
  35467. /**
  35468. * Indicates that textures need to be re-calculated for all submeshes
  35469. */
  35470. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35471. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35472. };
  35473. /**
  35474. * Indicates that fresnel needs to be re-calculated for all submeshes
  35475. */
  35476. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35477. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35478. };
  35479. /**
  35480. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35481. */
  35482. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35483. this._markAllSubMeshesAsDirty(function (defines) {
  35484. defines.markAsFresnelDirty();
  35485. defines.markAsMiscDirty();
  35486. });
  35487. };
  35488. /**
  35489. * Indicates that lights need to be re-calculated for all submeshes
  35490. */
  35491. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35492. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35493. };
  35494. /**
  35495. * Indicates that attributes need to be re-calculated for all submeshes
  35496. */
  35497. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35498. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35499. };
  35500. /**
  35501. * Indicates that misc needs to be re-calculated for all submeshes
  35502. */
  35503. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35504. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35505. };
  35506. /**
  35507. * Indicates that textures and misc need to be re-calculated for all submeshes
  35508. */
  35509. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35510. this._markAllSubMeshesAsDirty(function (defines) {
  35511. defines.markAsTexturesDirty();
  35512. defines.markAsMiscDirty();
  35513. });
  35514. };
  35515. /**
  35516. * Disposes the material
  35517. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35518. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35519. */
  35520. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35521. // Animations
  35522. this.getScene().stopAnimation(this);
  35523. this.getScene().freeProcessedMaterials();
  35524. // Remove from scene
  35525. var index = this._scene.materials.indexOf(this);
  35526. if (index >= 0) {
  35527. this._scene.materials.splice(index, 1);
  35528. }
  35529. // Remove from meshes
  35530. for (index = 0; index < this._scene.meshes.length; index++) {
  35531. var mesh = this._scene.meshes[index];
  35532. if (mesh.material === this) {
  35533. mesh.material = null;
  35534. if (mesh.geometry) {
  35535. var geometry = (mesh.geometry);
  35536. if (this.storeEffectOnSubMeshes) {
  35537. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35538. var subMesh = _a[_i];
  35539. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35540. if (forceDisposeEffect && subMesh._materialEffect) {
  35541. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35542. }
  35543. }
  35544. }
  35545. else {
  35546. geometry._releaseVertexArrayObject(this._effect);
  35547. }
  35548. }
  35549. }
  35550. }
  35551. this._uniformBuffer.dispose();
  35552. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35553. if (forceDisposeEffect && this._effect) {
  35554. if (!this.storeEffectOnSubMeshes) {
  35555. this._scene.getEngine()._releaseEffect(this._effect);
  35556. }
  35557. this._effect = null;
  35558. }
  35559. // Callback
  35560. this.onDisposeObservable.notifyObservers(this);
  35561. this.onDisposeObservable.clear();
  35562. this.onBindObservable.clear();
  35563. this.onUnBindObservable.clear();
  35564. };
  35565. /**
  35566. * Serializes this material
  35567. * @returns the serialized material object
  35568. */
  35569. Material.prototype.serialize = function () {
  35570. return BABYLON.SerializationHelper.Serialize(this);
  35571. };
  35572. /**
  35573. * Creates a MultiMaterial from parsed MultiMaterial data.
  35574. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35575. * @param scene defines the hosting scene
  35576. * @returns a new MultiMaterial
  35577. */
  35578. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35579. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35580. multiMaterial.id = parsedMultiMaterial.id;
  35581. if (BABYLON.Tags) {
  35582. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35583. }
  35584. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35585. var subMatId = parsedMultiMaterial.materials[matIndex];
  35586. if (subMatId) {
  35587. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35588. }
  35589. else {
  35590. multiMaterial.subMaterials.push(null);
  35591. }
  35592. }
  35593. return multiMaterial;
  35594. };
  35595. /**
  35596. * Creates a material from parsed material data
  35597. * @param parsedMaterial defines parsed material data
  35598. * @param scene defines the hosting scene
  35599. * @param rootUrl defines the root URL to use to load textures
  35600. * @returns a new material
  35601. */
  35602. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35603. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35604. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35605. }
  35606. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35607. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35608. if (!BABYLON.LegacyPBRMaterial) {
  35609. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35610. return;
  35611. }
  35612. }
  35613. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35614. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35615. };
  35616. // Triangle views
  35617. Material._TriangleFillMode = 0;
  35618. Material._WireFrameFillMode = 1;
  35619. Material._PointFillMode = 2;
  35620. // Draw modes
  35621. Material._PointListDrawMode = 3;
  35622. Material._LineListDrawMode = 4;
  35623. Material._LineLoopDrawMode = 5;
  35624. Material._LineStripDrawMode = 6;
  35625. Material._TriangleStripDrawMode = 7;
  35626. Material._TriangleFanDrawMode = 8;
  35627. /**
  35628. * Stores the clock-wise side orientation
  35629. */
  35630. Material._ClockWiseSideOrientation = 0;
  35631. /**
  35632. * Stores the counter clock-wise side orientation
  35633. */
  35634. Material._CounterClockWiseSideOrientation = 1;
  35635. /**
  35636. * The dirty texture flag value
  35637. */
  35638. Material._TextureDirtyFlag = 1;
  35639. /**
  35640. * The dirty light flag value
  35641. */
  35642. Material._LightDirtyFlag = 2;
  35643. /**
  35644. * The dirty fresnel flag value
  35645. */
  35646. Material._FresnelDirtyFlag = 4;
  35647. /**
  35648. * The dirty attribute flag value
  35649. */
  35650. Material._AttributesDirtyFlag = 8;
  35651. /**
  35652. * The dirty misc flag value
  35653. */
  35654. Material._MiscDirtyFlag = 16;
  35655. __decorate([
  35656. BABYLON.serialize()
  35657. ], Material.prototype, "id", void 0);
  35658. __decorate([
  35659. BABYLON.serialize()
  35660. ], Material.prototype, "name", void 0);
  35661. __decorate([
  35662. BABYLON.serialize()
  35663. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35664. __decorate([
  35665. BABYLON.serialize()
  35666. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35667. __decorate([
  35668. BABYLON.serialize()
  35669. ], Material.prototype, "state", void 0);
  35670. __decorate([
  35671. BABYLON.serialize("alpha")
  35672. ], Material.prototype, "_alpha", void 0);
  35673. __decorate([
  35674. BABYLON.serialize("backFaceCulling")
  35675. ], Material.prototype, "_backFaceCulling", void 0);
  35676. __decorate([
  35677. BABYLON.serialize()
  35678. ], Material.prototype, "sideOrientation", void 0);
  35679. __decorate([
  35680. BABYLON.serialize("alphaMode")
  35681. ], Material.prototype, "_alphaMode", void 0);
  35682. __decorate([
  35683. BABYLON.serialize()
  35684. ], Material.prototype, "_needDepthPrePass", void 0);
  35685. __decorate([
  35686. BABYLON.serialize()
  35687. ], Material.prototype, "disableDepthWrite", void 0);
  35688. __decorate([
  35689. BABYLON.serialize()
  35690. ], Material.prototype, "forceDepthWrite", void 0);
  35691. __decorate([
  35692. BABYLON.serialize()
  35693. ], Material.prototype, "separateCullingPass", void 0);
  35694. __decorate([
  35695. BABYLON.serialize("fogEnabled")
  35696. ], Material.prototype, "_fogEnabled", void 0);
  35697. __decorate([
  35698. BABYLON.serialize()
  35699. ], Material.prototype, "pointSize", void 0);
  35700. __decorate([
  35701. BABYLON.serialize()
  35702. ], Material.prototype, "zOffset", void 0);
  35703. __decorate([
  35704. BABYLON.serialize()
  35705. ], Material.prototype, "wireframe", null);
  35706. __decorate([
  35707. BABYLON.serialize()
  35708. ], Material.prototype, "pointsCloud", null);
  35709. __decorate([
  35710. BABYLON.serialize()
  35711. ], Material.prototype, "fillMode", null);
  35712. return Material;
  35713. }());
  35714. BABYLON.Material = Material;
  35715. })(BABYLON || (BABYLON = {}));
  35716. //# sourceMappingURL=babylon.material.js.map
  35717. var BABYLON;
  35718. (function (BABYLON) {
  35719. var UniformBuffer = /** @class */ (function () {
  35720. /**
  35721. * Uniform buffer objects.
  35722. *
  35723. * Handles blocks of uniform on the GPU.
  35724. *
  35725. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35726. *
  35727. * For more information, please refer to :
  35728. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35729. */
  35730. function UniformBuffer(engine, data, dynamic) {
  35731. this._engine = engine;
  35732. this._noUBO = !engine.supportsUniformBuffers;
  35733. this._dynamic = dynamic;
  35734. this._data = data || [];
  35735. this._uniformLocations = {};
  35736. this._uniformSizes = {};
  35737. this._uniformLocationPointer = 0;
  35738. this._needSync = false;
  35739. if (this._noUBO) {
  35740. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35741. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35742. this.updateFloat = this._updateFloatForEffect;
  35743. this.updateFloat2 = this._updateFloat2ForEffect;
  35744. this.updateFloat3 = this._updateFloat3ForEffect;
  35745. this.updateFloat4 = this._updateFloat4ForEffect;
  35746. this.updateMatrix = this._updateMatrixForEffect;
  35747. this.updateVector3 = this._updateVector3ForEffect;
  35748. this.updateVector4 = this._updateVector4ForEffect;
  35749. this.updateColor3 = this._updateColor3ForEffect;
  35750. this.updateColor4 = this._updateColor4ForEffect;
  35751. }
  35752. else {
  35753. this._engine._uniformBuffers.push(this);
  35754. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35755. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35756. this.updateFloat = this._updateFloatForUniform;
  35757. this.updateFloat2 = this._updateFloat2ForUniform;
  35758. this.updateFloat3 = this._updateFloat3ForUniform;
  35759. this.updateFloat4 = this._updateFloat4ForUniform;
  35760. this.updateMatrix = this._updateMatrixForUniform;
  35761. this.updateVector3 = this._updateVector3ForUniform;
  35762. this.updateVector4 = this._updateVector4ForUniform;
  35763. this.updateColor3 = this._updateColor3ForUniform;
  35764. this.updateColor4 = this._updateColor4ForUniform;
  35765. }
  35766. }
  35767. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35768. // Properties
  35769. /**
  35770. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35771. * or just falling back on setUniformXXX calls.
  35772. */
  35773. get: function () {
  35774. return !this._noUBO;
  35775. },
  35776. enumerable: true,
  35777. configurable: true
  35778. });
  35779. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35780. /**
  35781. * Indicates if the WebGL underlying uniform buffer is in sync
  35782. * with the javascript cache data.
  35783. */
  35784. get: function () {
  35785. return !this._needSync;
  35786. },
  35787. enumerable: true,
  35788. configurable: true
  35789. });
  35790. /**
  35791. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35792. * Also, a dynamic UniformBuffer will disable cache verification and always
  35793. * update the underlying WebGL uniform buffer to the GPU.
  35794. */
  35795. UniformBuffer.prototype.isDynamic = function () {
  35796. return this._dynamic !== undefined;
  35797. };
  35798. /**
  35799. * The data cache on JS side.
  35800. */
  35801. UniformBuffer.prototype.getData = function () {
  35802. return this._bufferData;
  35803. };
  35804. /**
  35805. * The underlying WebGL Uniform buffer.
  35806. */
  35807. UniformBuffer.prototype.getBuffer = function () {
  35808. return this._buffer;
  35809. };
  35810. /**
  35811. * std140 layout specifies how to align data within an UBO structure.
  35812. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35813. * for specs.
  35814. */
  35815. UniformBuffer.prototype._fillAlignment = function (size) {
  35816. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35817. // and 4x4 matrices
  35818. // TODO : change if other types are used
  35819. var alignment;
  35820. if (size <= 2) {
  35821. alignment = size;
  35822. }
  35823. else {
  35824. alignment = 4;
  35825. }
  35826. if ((this._uniformLocationPointer % alignment) !== 0) {
  35827. var oldPointer = this._uniformLocationPointer;
  35828. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35829. var diff = this._uniformLocationPointer - oldPointer;
  35830. for (var i = 0; i < diff; i++) {
  35831. this._data.push(0);
  35832. }
  35833. }
  35834. };
  35835. /**
  35836. * Adds an uniform in the buffer.
  35837. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35838. * for the layout to be correct !
  35839. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35840. * @param {number|number[]} size Data size, or data directly.
  35841. */
  35842. UniformBuffer.prototype.addUniform = function (name, size) {
  35843. if (this._noUBO) {
  35844. return;
  35845. }
  35846. if (this._uniformLocations[name] !== undefined) {
  35847. // Already existing uniform
  35848. return;
  35849. }
  35850. // This function must be called in the order of the shader layout !
  35851. // size can be the size of the uniform, or data directly
  35852. var data;
  35853. if (size instanceof Array) {
  35854. data = size;
  35855. size = data.length;
  35856. }
  35857. else {
  35858. size = size;
  35859. data = [];
  35860. // Fill with zeros
  35861. for (var i = 0; i < size; i++) {
  35862. data.push(0);
  35863. }
  35864. }
  35865. this._fillAlignment(size);
  35866. this._uniformSizes[name] = size;
  35867. this._uniformLocations[name] = this._uniformLocationPointer;
  35868. this._uniformLocationPointer += size;
  35869. for (var i = 0; i < size; i++) {
  35870. this._data.push(data[i]);
  35871. }
  35872. this._needSync = true;
  35873. };
  35874. /**
  35875. * Wrapper for addUniform.
  35876. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35877. * @param {Matrix} mat A 4x4 matrix.
  35878. */
  35879. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35880. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35881. };
  35882. /**
  35883. * Wrapper for addUniform.
  35884. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35885. * @param {number} x
  35886. * @param {number} y
  35887. */
  35888. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35889. var temp = [x, y];
  35890. this.addUniform(name, temp);
  35891. };
  35892. /**
  35893. * Wrapper for addUniform.
  35894. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35895. * @param {number} x
  35896. * @param {number} y
  35897. * @param {number} z
  35898. */
  35899. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35900. var temp = [x, y, z];
  35901. this.addUniform(name, temp);
  35902. };
  35903. /**
  35904. * Wrapper for addUniform.
  35905. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35906. * @param {Color3} color
  35907. */
  35908. UniformBuffer.prototype.addColor3 = function (name, color) {
  35909. var temp = new Array();
  35910. color.toArray(temp);
  35911. this.addUniform(name, temp);
  35912. };
  35913. /**
  35914. * Wrapper for addUniform.
  35915. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35916. * @param {Color3} color
  35917. * @param {number} alpha
  35918. */
  35919. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35920. var temp = new Array();
  35921. color.toArray(temp);
  35922. temp.push(alpha);
  35923. this.addUniform(name, temp);
  35924. };
  35925. /**
  35926. * Wrapper for addUniform.
  35927. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35928. * @param {Vector3} vector
  35929. */
  35930. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35931. var temp = new Array();
  35932. vector.toArray(temp);
  35933. this.addUniform(name, temp);
  35934. };
  35935. /**
  35936. * Wrapper for addUniform.
  35937. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35938. */
  35939. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35940. this.addUniform(name, 12);
  35941. };
  35942. /**
  35943. * Wrapper for addUniform.
  35944. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35945. */
  35946. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35947. this.addUniform(name, 8);
  35948. };
  35949. /**
  35950. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35951. */
  35952. UniformBuffer.prototype.create = function () {
  35953. if (this._noUBO) {
  35954. return;
  35955. }
  35956. if (this._buffer) {
  35957. return; // nothing to do
  35958. }
  35959. // See spec, alignment must be filled as a vec4
  35960. this._fillAlignment(4);
  35961. this._bufferData = new Float32Array(this._data);
  35962. this._rebuild();
  35963. this._needSync = true;
  35964. };
  35965. UniformBuffer.prototype._rebuild = function () {
  35966. if (this._noUBO) {
  35967. return;
  35968. }
  35969. if (this._dynamic) {
  35970. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35971. }
  35972. else {
  35973. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35974. }
  35975. };
  35976. /**
  35977. * Updates the WebGL Uniform Buffer on the GPU.
  35978. * If the `dynamic` flag is set to true, no cache comparison is done.
  35979. * Otherwise, the buffer will be updated only if the cache differs.
  35980. */
  35981. UniformBuffer.prototype.update = function () {
  35982. if (!this._buffer) {
  35983. this.create();
  35984. return;
  35985. }
  35986. if (!this._dynamic && !this._needSync) {
  35987. return;
  35988. }
  35989. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35990. this._needSync = false;
  35991. };
  35992. /**
  35993. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35994. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35995. * @param {number[]|Float32Array} data Flattened data
  35996. * @param {number} size Size of the data.
  35997. */
  35998. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35999. var location = this._uniformLocations[uniformName];
  36000. if (location === undefined) {
  36001. if (this._buffer) {
  36002. // Cannot add an uniform if the buffer is already created
  36003. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36004. return;
  36005. }
  36006. this.addUniform(uniformName, size);
  36007. location = this._uniformLocations[uniformName];
  36008. }
  36009. if (!this._buffer) {
  36010. this.create();
  36011. }
  36012. if (!this._dynamic) {
  36013. // Cache for static uniform buffers
  36014. var changed = false;
  36015. for (var i = 0; i < size; i++) {
  36016. if (this._bufferData[location + i] !== data[i]) {
  36017. changed = true;
  36018. this._bufferData[location + i] = data[i];
  36019. }
  36020. }
  36021. this._needSync = this._needSync || changed;
  36022. }
  36023. else {
  36024. // No cache for dynamic
  36025. for (var i = 0; i < size; i++) {
  36026. this._bufferData[location + i] = data[i];
  36027. }
  36028. }
  36029. };
  36030. // Update methods
  36031. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36032. // To match std140, matrix must be realigned
  36033. for (var i = 0; i < 3; i++) {
  36034. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36035. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36036. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36037. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36038. }
  36039. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36040. };
  36041. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36042. this._currentEffect.setMatrix3x3(name, matrix);
  36043. };
  36044. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36045. this._currentEffect.setMatrix2x2(name, matrix);
  36046. };
  36047. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36048. // To match std140, matrix must be realigned
  36049. for (var i = 0; i < 2; i++) {
  36050. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36051. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36052. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36053. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36054. }
  36055. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36056. };
  36057. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36058. this._currentEffect.setFloat(name, x);
  36059. };
  36060. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36061. UniformBuffer._tempBuffer[0] = x;
  36062. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36063. };
  36064. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36065. if (suffix === void 0) { suffix = ""; }
  36066. this._currentEffect.setFloat2(name + suffix, x, y);
  36067. };
  36068. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36069. if (suffix === void 0) { suffix = ""; }
  36070. UniformBuffer._tempBuffer[0] = x;
  36071. UniformBuffer._tempBuffer[1] = y;
  36072. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36073. };
  36074. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36075. if (suffix === void 0) { suffix = ""; }
  36076. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36077. };
  36078. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36079. if (suffix === void 0) { suffix = ""; }
  36080. UniformBuffer._tempBuffer[0] = x;
  36081. UniformBuffer._tempBuffer[1] = y;
  36082. UniformBuffer._tempBuffer[2] = z;
  36083. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36084. };
  36085. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36086. if (suffix === void 0) { suffix = ""; }
  36087. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36088. };
  36089. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36090. if (suffix === void 0) { suffix = ""; }
  36091. UniformBuffer._tempBuffer[0] = x;
  36092. UniformBuffer._tempBuffer[1] = y;
  36093. UniformBuffer._tempBuffer[2] = z;
  36094. UniformBuffer._tempBuffer[3] = w;
  36095. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36096. };
  36097. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36098. this._currentEffect.setMatrix(name, mat);
  36099. };
  36100. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36101. this.updateUniform(name, mat.toArray(), 16);
  36102. };
  36103. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36104. this._currentEffect.setVector3(name, vector);
  36105. };
  36106. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36107. vector.toArray(UniformBuffer._tempBuffer);
  36108. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36109. };
  36110. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36111. this._currentEffect.setVector4(name, vector);
  36112. };
  36113. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36114. vector.toArray(UniformBuffer._tempBuffer);
  36115. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36116. };
  36117. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36118. if (suffix === void 0) { suffix = ""; }
  36119. this._currentEffect.setColor3(name + suffix, color);
  36120. };
  36121. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36122. if (suffix === void 0) { suffix = ""; }
  36123. color.toArray(UniformBuffer._tempBuffer);
  36124. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36125. };
  36126. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36127. if (suffix === void 0) { suffix = ""; }
  36128. this._currentEffect.setColor4(name + suffix, color, alpha);
  36129. };
  36130. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36131. if (suffix === void 0) { suffix = ""; }
  36132. color.toArray(UniformBuffer._tempBuffer);
  36133. UniformBuffer._tempBuffer[3] = alpha;
  36134. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36135. };
  36136. /**
  36137. * Sets a sampler uniform on the effect.
  36138. * @param {string} name Name of the sampler.
  36139. * @param {Texture} texture
  36140. */
  36141. UniformBuffer.prototype.setTexture = function (name, texture) {
  36142. this._currentEffect.setTexture(name, texture);
  36143. };
  36144. /**
  36145. * Directly updates the value of the uniform in the cache AND on the GPU.
  36146. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36147. * @param {number[]|Float32Array} data Flattened data
  36148. */
  36149. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36150. this.updateUniform(uniformName, data, data.length);
  36151. this.update();
  36152. };
  36153. /**
  36154. * Binds this uniform buffer to an effect.
  36155. * @param {Effect} effect
  36156. * @param {string} name Name of the uniform block in the shader.
  36157. */
  36158. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36159. this._currentEffect = effect;
  36160. if (this._noUBO || !this._buffer) {
  36161. return;
  36162. }
  36163. effect.bindUniformBuffer(this._buffer, name);
  36164. };
  36165. /**
  36166. * Disposes the uniform buffer.
  36167. */
  36168. UniformBuffer.prototype.dispose = function () {
  36169. if (this._noUBO) {
  36170. return;
  36171. }
  36172. var index = this._engine._uniformBuffers.indexOf(this);
  36173. if (index !== -1) {
  36174. this._engine._uniformBuffers.splice(index, 1);
  36175. }
  36176. if (!this._buffer) {
  36177. return;
  36178. }
  36179. if (this._engine._releaseBuffer(this._buffer)) {
  36180. this._buffer = null;
  36181. }
  36182. };
  36183. // Pool for avoiding memory leaks
  36184. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36185. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36186. return UniformBuffer;
  36187. }());
  36188. BABYLON.UniformBuffer = UniformBuffer;
  36189. })(BABYLON || (BABYLON = {}));
  36190. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36191. var BABYLON;
  36192. (function (BABYLON) {
  36193. /**
  36194. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36195. */
  36196. var VertexData = /** @class */ (function () {
  36197. function VertexData() {
  36198. }
  36199. /**
  36200. * Uses the passed data array to set the set the values for the specified kind of data
  36201. * @param data a linear array of floating numbers
  36202. * @param kind the type of data that is being set, eg positions, colors etc
  36203. */
  36204. VertexData.prototype.set = function (data, kind) {
  36205. switch (kind) {
  36206. case BABYLON.VertexBuffer.PositionKind:
  36207. this.positions = data;
  36208. break;
  36209. case BABYLON.VertexBuffer.NormalKind:
  36210. this.normals = data;
  36211. break;
  36212. case BABYLON.VertexBuffer.TangentKind:
  36213. this.tangents = data;
  36214. break;
  36215. case BABYLON.VertexBuffer.UVKind:
  36216. this.uvs = data;
  36217. break;
  36218. case BABYLON.VertexBuffer.UV2Kind:
  36219. this.uvs2 = data;
  36220. break;
  36221. case BABYLON.VertexBuffer.UV3Kind:
  36222. this.uvs3 = data;
  36223. break;
  36224. case BABYLON.VertexBuffer.UV4Kind:
  36225. this.uvs4 = data;
  36226. break;
  36227. case BABYLON.VertexBuffer.UV5Kind:
  36228. this.uvs5 = data;
  36229. break;
  36230. case BABYLON.VertexBuffer.UV6Kind:
  36231. this.uvs6 = data;
  36232. break;
  36233. case BABYLON.VertexBuffer.ColorKind:
  36234. this.colors = data;
  36235. break;
  36236. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36237. this.matricesIndices = data;
  36238. break;
  36239. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36240. this.matricesWeights = data;
  36241. break;
  36242. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36243. this.matricesIndicesExtra = data;
  36244. break;
  36245. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36246. this.matricesWeightsExtra = data;
  36247. break;
  36248. }
  36249. };
  36250. /**
  36251. * Associates the vertexData to the passed Mesh.
  36252. * Sets it as updatable or not (default `false`)
  36253. * @param mesh the mesh the vertexData is applied to
  36254. * @param updatable when used and having the value true allows new data to update the vertexData
  36255. * @returns the VertexData
  36256. */
  36257. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36258. this._applyTo(mesh, updatable);
  36259. return this;
  36260. };
  36261. /**
  36262. * Associates the vertexData to the passed Geometry.
  36263. * Sets it as updatable or not (default `false`)
  36264. * @param geometry the geometry the vertexData is applied to
  36265. * @param updatable when used and having the value true allows new data to update the vertexData
  36266. * @returns VertexData
  36267. */
  36268. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36269. this._applyTo(geometry, updatable);
  36270. return this;
  36271. };
  36272. /**
  36273. * Updates the associated mesh
  36274. * @param mesh the mesh to be updated
  36275. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36276. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36277. * @returns VertexData
  36278. */
  36279. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36280. this._update(mesh);
  36281. return this;
  36282. };
  36283. /**
  36284. * Updates the associated geometry
  36285. * @param geometry the geometry to be updated
  36286. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36287. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36288. * @returns VertexData.
  36289. */
  36290. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36291. this._update(geometry);
  36292. return this;
  36293. };
  36294. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36295. if (updatable === void 0) { updatable = false; }
  36296. if (this.positions) {
  36297. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36298. }
  36299. if (this.normals) {
  36300. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36301. }
  36302. if (this.tangents) {
  36303. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36304. }
  36305. if (this.uvs) {
  36306. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36307. }
  36308. if (this.uvs2) {
  36309. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36310. }
  36311. if (this.uvs3) {
  36312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36313. }
  36314. if (this.uvs4) {
  36315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36316. }
  36317. if (this.uvs5) {
  36318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36319. }
  36320. if (this.uvs6) {
  36321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36322. }
  36323. if (this.colors) {
  36324. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36325. }
  36326. if (this.matricesIndices) {
  36327. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36328. }
  36329. if (this.matricesWeights) {
  36330. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36331. }
  36332. if (this.matricesIndicesExtra) {
  36333. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36334. }
  36335. if (this.matricesWeightsExtra) {
  36336. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36337. }
  36338. if (this.indices) {
  36339. meshOrGeometry.setIndices(this.indices, null, updatable);
  36340. }
  36341. return this;
  36342. };
  36343. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36344. if (this.positions) {
  36345. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36346. }
  36347. if (this.normals) {
  36348. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36349. }
  36350. if (this.tangents) {
  36351. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36352. }
  36353. if (this.uvs) {
  36354. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36355. }
  36356. if (this.uvs2) {
  36357. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36358. }
  36359. if (this.uvs3) {
  36360. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36361. }
  36362. if (this.uvs4) {
  36363. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36364. }
  36365. if (this.uvs5) {
  36366. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36367. }
  36368. if (this.uvs6) {
  36369. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36370. }
  36371. if (this.colors) {
  36372. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36373. }
  36374. if (this.matricesIndices) {
  36375. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36376. }
  36377. if (this.matricesWeights) {
  36378. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36379. }
  36380. if (this.matricesIndicesExtra) {
  36381. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36382. }
  36383. if (this.matricesWeightsExtra) {
  36384. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36385. }
  36386. if (this.indices) {
  36387. meshOrGeometry.setIndices(this.indices, null);
  36388. }
  36389. return this;
  36390. };
  36391. /**
  36392. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36393. * @param matrix the transforming matrix
  36394. * @returns the VertexData
  36395. */
  36396. VertexData.prototype.transform = function (matrix) {
  36397. var transformed = BABYLON.Vector3.Zero();
  36398. var index;
  36399. if (this.positions) {
  36400. var position = BABYLON.Vector3.Zero();
  36401. for (index = 0; index < this.positions.length; index += 3) {
  36402. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36403. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36404. this.positions[index] = transformed.x;
  36405. this.positions[index + 1] = transformed.y;
  36406. this.positions[index + 2] = transformed.z;
  36407. }
  36408. }
  36409. if (this.normals) {
  36410. var normal = BABYLON.Vector3.Zero();
  36411. for (index = 0; index < this.normals.length; index += 3) {
  36412. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36413. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36414. this.normals[index] = transformed.x;
  36415. this.normals[index + 1] = transformed.y;
  36416. this.normals[index + 2] = transformed.z;
  36417. }
  36418. }
  36419. if (this.tangents) {
  36420. var tangent = BABYLON.Vector4.Zero();
  36421. var tangentTransformed = BABYLON.Vector4.Zero();
  36422. for (index = 0; index < this.tangents.length; index += 4) {
  36423. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36424. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36425. this.tangents[index] = tangentTransformed.x;
  36426. this.tangents[index + 1] = tangentTransformed.y;
  36427. this.tangents[index + 2] = tangentTransformed.z;
  36428. this.tangents[index + 3] = tangentTransformed.w;
  36429. }
  36430. }
  36431. return this;
  36432. };
  36433. /**
  36434. * Merges the passed VertexData into the current one
  36435. * @param other the VertexData to be merged into the current one
  36436. * @returns the modified VertexData
  36437. */
  36438. VertexData.prototype.merge = function (other) {
  36439. this._validate();
  36440. other._validate();
  36441. if (!this.normals !== !other.normals ||
  36442. !this.tangents !== !other.tangents ||
  36443. !this.uvs !== !other.uvs ||
  36444. !this.uvs2 !== !other.uvs2 ||
  36445. !this.uvs3 !== !other.uvs3 ||
  36446. !this.uvs4 !== !other.uvs4 ||
  36447. !this.uvs5 !== !other.uvs5 ||
  36448. !this.uvs6 !== !other.uvs6 ||
  36449. !this.colors !== !other.colors ||
  36450. !this.matricesIndices !== !other.matricesIndices ||
  36451. !this.matricesWeights !== !other.matricesWeights ||
  36452. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36453. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36454. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36455. }
  36456. if (other.indices) {
  36457. if (!this.indices) {
  36458. this.indices = [];
  36459. }
  36460. var offset = this.positions ? this.positions.length / 3 : 0;
  36461. for (var index = 0; index < other.indices.length; index++) {
  36462. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36463. this.indices.push(other.indices[index] + offset);
  36464. }
  36465. }
  36466. this.positions = this._mergeElement(this.positions, other.positions);
  36467. this.normals = this._mergeElement(this.normals, other.normals);
  36468. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36469. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36470. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36471. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36472. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36473. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36474. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36475. this.colors = this._mergeElement(this.colors, other.colors);
  36476. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36477. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36478. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36479. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36480. return this;
  36481. };
  36482. VertexData.prototype._mergeElement = function (source, other) {
  36483. if (!source) {
  36484. return other;
  36485. }
  36486. if (!other) {
  36487. return source;
  36488. }
  36489. var len = other.length + source.length;
  36490. var isSrcTypedArray = source instanceof Float32Array;
  36491. var isOthTypedArray = other instanceof Float32Array;
  36492. // use non-loop method when the source is Float32Array
  36493. if (isSrcTypedArray) {
  36494. var ret32 = new Float32Array(len);
  36495. ret32.set(source);
  36496. ret32.set(other, source.length);
  36497. return ret32;
  36498. // source is number[], when other is also use concat
  36499. }
  36500. else if (!isOthTypedArray) {
  36501. return source.concat(other);
  36502. // source is a number[], but other is a Float32Array, loop required
  36503. }
  36504. else {
  36505. var ret = source.slice(0); // copy source to a separate array
  36506. for (var i = 0, len = other.length; i < len; i++) {
  36507. ret.push(other[i]);
  36508. }
  36509. return ret;
  36510. }
  36511. };
  36512. VertexData.prototype._validate = function () {
  36513. if (!this.positions) {
  36514. throw new Error("Positions are required");
  36515. }
  36516. var getElementCount = function (kind, values) {
  36517. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36518. if ((values.length % stride) !== 0) {
  36519. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36520. }
  36521. return values.length / stride;
  36522. };
  36523. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36524. var validateElementCount = function (kind, values) {
  36525. var elementCount = getElementCount(kind, values);
  36526. if (elementCount !== positionsElementCount) {
  36527. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36528. }
  36529. };
  36530. if (this.normals)
  36531. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36532. if (this.tangents)
  36533. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36534. if (this.uvs)
  36535. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36536. if (this.uvs2)
  36537. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36538. if (this.uvs3)
  36539. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36540. if (this.uvs4)
  36541. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36542. if (this.uvs5)
  36543. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36544. if (this.uvs6)
  36545. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36546. if (this.colors)
  36547. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36548. if (this.matricesIndices)
  36549. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36550. if (this.matricesWeights)
  36551. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36552. if (this.matricesIndicesExtra)
  36553. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36554. if (this.matricesWeightsExtra)
  36555. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36556. };
  36557. /**
  36558. * Serializes the VertexData
  36559. * @returns a serialized object
  36560. */
  36561. VertexData.prototype.serialize = function () {
  36562. var serializationObject = this.serialize();
  36563. if (this.positions) {
  36564. serializationObject.positions = this.positions;
  36565. }
  36566. if (this.normals) {
  36567. serializationObject.normals = this.normals;
  36568. }
  36569. if (this.tangents) {
  36570. serializationObject.tangents = this.tangents;
  36571. }
  36572. if (this.uvs) {
  36573. serializationObject.uvs = this.uvs;
  36574. }
  36575. if (this.uvs2) {
  36576. serializationObject.uvs2 = this.uvs2;
  36577. }
  36578. if (this.uvs3) {
  36579. serializationObject.uvs3 = this.uvs3;
  36580. }
  36581. if (this.uvs4) {
  36582. serializationObject.uvs4 = this.uvs4;
  36583. }
  36584. if (this.uvs5) {
  36585. serializationObject.uvs5 = this.uvs5;
  36586. }
  36587. if (this.uvs6) {
  36588. serializationObject.uvs6 = this.uvs6;
  36589. }
  36590. if (this.colors) {
  36591. serializationObject.colors = this.colors;
  36592. }
  36593. if (this.matricesIndices) {
  36594. serializationObject.matricesIndices = this.matricesIndices;
  36595. serializationObject.matricesIndices._isExpanded = true;
  36596. }
  36597. if (this.matricesWeights) {
  36598. serializationObject.matricesWeights = this.matricesWeights;
  36599. }
  36600. if (this.matricesIndicesExtra) {
  36601. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36602. serializationObject.matricesIndicesExtra._isExpanded = true;
  36603. }
  36604. if (this.matricesWeightsExtra) {
  36605. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36606. }
  36607. serializationObject.indices = this.indices;
  36608. return serializationObject;
  36609. };
  36610. // Statics
  36611. /**
  36612. * Extracts the vertexData from a mesh
  36613. * @param mesh the mesh from which to extract the VertexData
  36614. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36615. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36616. * @returns the object VertexData associated to the passed mesh
  36617. */
  36618. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36619. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36620. };
  36621. /**
  36622. * Extracts the vertexData from the geometry
  36623. * @param geometry the geometry from which to extract the VertexData
  36624. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36625. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36626. * @returns the object VertexData associated to the passed mesh
  36627. */
  36628. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36629. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36630. };
  36631. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36632. var result = new VertexData();
  36633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36634. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36635. }
  36636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36637. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36638. }
  36639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36640. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36641. }
  36642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36643. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36644. }
  36645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36646. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36647. }
  36648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36649. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36650. }
  36651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36652. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36653. }
  36654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36655. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36656. }
  36657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36658. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36659. }
  36660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36661. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36662. }
  36663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36664. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36665. }
  36666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36667. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36668. }
  36669. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36670. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36671. }
  36672. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36673. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36674. }
  36675. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36676. return result;
  36677. };
  36678. /**
  36679. * Creates the VertexData for a Ribbon
  36680. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36681. * * pathArray array of paths, each of which an array of successive Vector3
  36682. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36683. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36684. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36685. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36686. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36687. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36688. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36689. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36690. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36691. * @returns the VertexData of the ribbon
  36692. */
  36693. VertexData.CreateRibbon = function (options) {
  36694. var pathArray = options.pathArray;
  36695. var closeArray = options.closeArray || false;
  36696. var closePath = options.closePath || false;
  36697. var invertUV = options.invertUV || false;
  36698. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36699. var offset = options.offset || defaultOffset;
  36700. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36702. var customUV = options.uvs;
  36703. var customColors = options.colors;
  36704. var positions = [];
  36705. var indices = [];
  36706. var normals = [];
  36707. var uvs = [];
  36708. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36709. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36710. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36711. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36712. var minlg; // minimal length among all paths from pathArray
  36713. var lg = []; // array of path lengths : nb of vertex per path
  36714. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36715. var p; // path iterator
  36716. var i; // point iterator
  36717. var j; // point iterator
  36718. // if single path in pathArray
  36719. if (pathArray.length < 2) {
  36720. var ar1 = [];
  36721. var ar2 = [];
  36722. for (i = 0; i < pathArray[0].length - offset; i++) {
  36723. ar1.push(pathArray[0][i]);
  36724. ar2.push(pathArray[0][i + offset]);
  36725. }
  36726. pathArray = [ar1, ar2];
  36727. }
  36728. // positions and horizontal distances (u)
  36729. var idc = 0;
  36730. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36731. var path;
  36732. var l;
  36733. minlg = pathArray[0].length;
  36734. var vectlg;
  36735. var dist;
  36736. for (p = 0; p < pathArray.length; p++) {
  36737. uTotalDistance[p] = 0;
  36738. us[p] = [0];
  36739. path = pathArray[p];
  36740. l = path.length;
  36741. minlg = (minlg < l) ? minlg : l;
  36742. j = 0;
  36743. while (j < l) {
  36744. positions.push(path[j].x, path[j].y, path[j].z);
  36745. if (j > 0) {
  36746. vectlg = path[j].subtract(path[j - 1]).length();
  36747. dist = vectlg + uTotalDistance[p];
  36748. us[p].push(dist);
  36749. uTotalDistance[p] = dist;
  36750. }
  36751. j++;
  36752. }
  36753. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36754. j--;
  36755. positions.push(path[0].x, path[0].y, path[0].z);
  36756. vectlg = path[j].subtract(path[0]).length();
  36757. dist = vectlg + uTotalDistance[p];
  36758. us[p].push(dist);
  36759. uTotalDistance[p] = dist;
  36760. }
  36761. lg[p] = l + closePathCorr;
  36762. idx[p] = idc;
  36763. idc += (l + closePathCorr);
  36764. }
  36765. // vertical distances (v)
  36766. var path1;
  36767. var path2;
  36768. var vertex1 = null;
  36769. var vertex2 = null;
  36770. for (i = 0; i < minlg + closePathCorr; i++) {
  36771. vTotalDistance[i] = 0;
  36772. vs[i] = [0];
  36773. for (p = 0; p < pathArray.length - 1; p++) {
  36774. path1 = pathArray[p];
  36775. path2 = pathArray[p + 1];
  36776. if (i === minlg) { // closePath
  36777. vertex1 = path1[0];
  36778. vertex2 = path2[0];
  36779. }
  36780. else {
  36781. vertex1 = path1[i];
  36782. vertex2 = path2[i];
  36783. }
  36784. vectlg = vertex2.subtract(vertex1).length();
  36785. dist = vectlg + vTotalDistance[i];
  36786. vs[i].push(dist);
  36787. vTotalDistance[i] = dist;
  36788. }
  36789. if (closeArray && vertex2 && vertex1) {
  36790. path1 = pathArray[p];
  36791. path2 = pathArray[0];
  36792. if (i === minlg) { // closePath
  36793. vertex2 = path2[0];
  36794. }
  36795. vectlg = vertex2.subtract(vertex1).length();
  36796. dist = vectlg + vTotalDistance[i];
  36797. vTotalDistance[i] = dist;
  36798. }
  36799. }
  36800. // uvs
  36801. var u;
  36802. var v;
  36803. if (customUV) {
  36804. for (p = 0; p < customUV.length; p++) {
  36805. uvs.push(customUV[p].x, customUV[p].y);
  36806. }
  36807. }
  36808. else {
  36809. for (p = 0; p < pathArray.length; p++) {
  36810. for (i = 0; i < minlg + closePathCorr; i++) {
  36811. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36812. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36813. if (invertUV) {
  36814. uvs.push(v, u);
  36815. }
  36816. else {
  36817. uvs.push(u, v);
  36818. }
  36819. }
  36820. }
  36821. }
  36822. // indices
  36823. p = 0; // path index
  36824. var pi = 0; // positions array index
  36825. var l1 = lg[p] - 1; // path1 length
  36826. var l2 = lg[p + 1] - 1; // path2 length
  36827. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36828. var shft = idx[1] - idx[0]; // shift
  36829. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36830. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36831. // 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
  36832. indices.push(pi, pi + shft, pi + 1);
  36833. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36834. pi += 1;
  36835. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36836. p++;
  36837. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36838. shft = idx[0] - idx[p];
  36839. l1 = lg[p] - 1;
  36840. l2 = lg[0] - 1;
  36841. }
  36842. else {
  36843. shft = idx[p + 1] - idx[p];
  36844. l1 = lg[p] - 1;
  36845. l2 = lg[p + 1] - 1;
  36846. }
  36847. pi = idx[p];
  36848. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36849. }
  36850. }
  36851. // normals
  36852. VertexData.ComputeNormals(positions, indices, normals);
  36853. if (closePath) { // update both the first and last vertex normals to their average value
  36854. var indexFirst = 0;
  36855. var indexLast = 0;
  36856. for (p = 0; p < pathArray.length; p++) {
  36857. indexFirst = idx[p] * 3;
  36858. if (p + 1 < pathArray.length) {
  36859. indexLast = (idx[p + 1] - 1) * 3;
  36860. }
  36861. else {
  36862. indexLast = normals.length - 3;
  36863. }
  36864. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36865. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36866. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36867. normals[indexLast] = normals[indexFirst];
  36868. normals[indexLast + 1] = normals[indexFirst + 1];
  36869. normals[indexLast + 2] = normals[indexFirst + 2];
  36870. }
  36871. }
  36872. // sides
  36873. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36874. // Colors
  36875. var colors = null;
  36876. if (customColors) {
  36877. colors = new Float32Array(customColors.length * 4);
  36878. for (var c = 0; c < customColors.length; c++) {
  36879. colors[c * 4] = customColors[c].r;
  36880. colors[c * 4 + 1] = customColors[c].g;
  36881. colors[c * 4 + 2] = customColors[c].b;
  36882. colors[c * 4 + 3] = customColors[c].a;
  36883. }
  36884. }
  36885. // Result
  36886. var vertexData = new VertexData();
  36887. var positions32 = new Float32Array(positions);
  36888. var normals32 = new Float32Array(normals);
  36889. var uvs32 = new Float32Array(uvs);
  36890. vertexData.indices = indices;
  36891. vertexData.positions = positions32;
  36892. vertexData.normals = normals32;
  36893. vertexData.uvs = uvs32;
  36894. if (colors) {
  36895. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36896. }
  36897. if (closePath) {
  36898. vertexData._idx = idx;
  36899. }
  36900. return vertexData;
  36901. };
  36902. /**
  36903. * Creates the VertexData for a box
  36904. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36905. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36906. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36907. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36908. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36909. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36910. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36911. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36912. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36913. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36914. * @returns the VertexData of the box
  36915. */
  36916. VertexData.CreateBox = function (options) {
  36917. var normalsSource = [
  36918. new BABYLON.Vector3(0, 0, 1),
  36919. new BABYLON.Vector3(0, 0, -1),
  36920. new BABYLON.Vector3(1, 0, 0),
  36921. new BABYLON.Vector3(-1, 0, 0),
  36922. new BABYLON.Vector3(0, 1, 0),
  36923. new BABYLON.Vector3(0, -1, 0)
  36924. ];
  36925. var indices = [];
  36926. var positions = [];
  36927. var normals = [];
  36928. var uvs = [];
  36929. var width = options.width || options.size || 1;
  36930. var height = options.height || options.size || 1;
  36931. var depth = options.depth || options.size || 1;
  36932. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36933. var faceUV = options.faceUV || new Array(6);
  36934. var faceColors = options.faceColors;
  36935. var colors = [];
  36936. // default face colors and UV if undefined
  36937. for (var f = 0; f < 6; f++) {
  36938. if (faceUV[f] === undefined) {
  36939. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36940. }
  36941. if (faceColors && faceColors[f] === undefined) {
  36942. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36943. }
  36944. }
  36945. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36946. // Create each face in turn.
  36947. for (var index = 0; index < normalsSource.length; index++) {
  36948. var normal = normalsSource[index];
  36949. // Get two vectors perpendicular to the face normal and to each other.
  36950. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36951. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36952. // Six indices (two triangles) per face.
  36953. var verticesLength = positions.length / 3;
  36954. indices.push(verticesLength);
  36955. indices.push(verticesLength + 1);
  36956. indices.push(verticesLength + 2);
  36957. indices.push(verticesLength);
  36958. indices.push(verticesLength + 2);
  36959. indices.push(verticesLength + 3);
  36960. // Four vertices per face.
  36961. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36962. positions.push(vertex.x, vertex.y, vertex.z);
  36963. normals.push(normal.x, normal.y, normal.z);
  36964. uvs.push(faceUV[index].z, faceUV[index].w);
  36965. if (faceColors) {
  36966. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36967. }
  36968. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36969. positions.push(vertex.x, vertex.y, vertex.z);
  36970. normals.push(normal.x, normal.y, normal.z);
  36971. uvs.push(faceUV[index].x, faceUV[index].w);
  36972. if (faceColors) {
  36973. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36974. }
  36975. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36976. positions.push(vertex.x, vertex.y, vertex.z);
  36977. normals.push(normal.x, normal.y, normal.z);
  36978. uvs.push(faceUV[index].x, faceUV[index].y);
  36979. if (faceColors) {
  36980. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36981. }
  36982. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36983. positions.push(vertex.x, vertex.y, vertex.z);
  36984. normals.push(normal.x, normal.y, normal.z);
  36985. uvs.push(faceUV[index].z, faceUV[index].y);
  36986. if (faceColors) {
  36987. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36988. }
  36989. }
  36990. // sides
  36991. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36992. // Result
  36993. var vertexData = new VertexData();
  36994. vertexData.indices = indices;
  36995. vertexData.positions = positions;
  36996. vertexData.normals = normals;
  36997. vertexData.uvs = uvs;
  36998. if (faceColors) {
  36999. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37000. vertexData.colors = totalColors;
  37001. }
  37002. return vertexData;
  37003. };
  37004. /**
  37005. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37006. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37007. * * segments sets the number of horizontal strips optional, default 32
  37008. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37009. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37010. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37011. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37012. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37013. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37014. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37015. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37016. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37017. * @returns the VertexData of the ellipsoid
  37018. */
  37019. VertexData.CreateSphere = function (options) {
  37020. var segments = options.segments || 32;
  37021. var diameterX = options.diameterX || options.diameter || 1;
  37022. var diameterY = options.diameterY || options.diameter || 1;
  37023. var diameterZ = options.diameterZ || options.diameter || 1;
  37024. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37025. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37026. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37027. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37028. var totalZRotationSteps = 2 + segments;
  37029. var totalYRotationSteps = 2 * totalZRotationSteps;
  37030. var indices = [];
  37031. var positions = [];
  37032. var normals = [];
  37033. var uvs = [];
  37034. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37035. var normalizedZ = zRotationStep / totalZRotationSteps;
  37036. var angleZ = normalizedZ * Math.PI * slice;
  37037. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37038. var normalizedY = yRotationStep / totalYRotationSteps;
  37039. var angleY = normalizedY * Math.PI * 2 * arc;
  37040. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37041. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37042. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37043. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37044. var vertex = complete.multiply(radius);
  37045. var normal = complete.divide(radius).normalize();
  37046. positions.push(vertex.x, vertex.y, vertex.z);
  37047. normals.push(normal.x, normal.y, normal.z);
  37048. uvs.push(normalizedY, normalizedZ);
  37049. }
  37050. if (zRotationStep > 0) {
  37051. var verticesCount = positions.length / 3;
  37052. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37053. indices.push((firstIndex));
  37054. indices.push((firstIndex + 1));
  37055. indices.push(firstIndex + totalYRotationSteps + 1);
  37056. indices.push((firstIndex + totalYRotationSteps + 1));
  37057. indices.push((firstIndex + 1));
  37058. indices.push((firstIndex + totalYRotationSteps + 2));
  37059. }
  37060. }
  37061. }
  37062. // Sides
  37063. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37064. // Result
  37065. var vertexData = new VertexData();
  37066. vertexData.indices = indices;
  37067. vertexData.positions = positions;
  37068. vertexData.normals = normals;
  37069. vertexData.uvs = uvs;
  37070. return vertexData;
  37071. };
  37072. /**
  37073. * Creates the VertexData for a cylinder, cone or prism
  37074. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37075. * * height sets the height (y direction) of the cylinder, optional, default 2
  37076. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37077. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37078. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37079. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37080. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37081. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37082. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37083. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37084. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37085. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37086. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37087. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37088. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37089. * @returns the VertexData of the cylinder, cone or prism
  37090. */
  37091. VertexData.CreateCylinder = function (options) {
  37092. var height = options.height || 2;
  37093. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37094. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37095. var tessellation = options.tessellation || 24;
  37096. var subdivisions = options.subdivisions || 1;
  37097. var hasRings = options.hasRings ? true : false;
  37098. var enclose = options.enclose ? true : false;
  37099. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37100. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37101. var faceUV = options.faceUV || new Array(3);
  37102. var faceColors = options.faceColors;
  37103. // default face colors and UV if undefined
  37104. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37105. var ringNb = (hasRings) ? subdivisions : 1;
  37106. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37107. var f;
  37108. for (f = 0; f < surfaceNb; f++) {
  37109. if (faceColors && faceColors[f] === undefined) {
  37110. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37111. }
  37112. }
  37113. for (f = 0; f < surfaceNb; f++) {
  37114. if (faceUV && faceUV[f] === undefined) {
  37115. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37116. }
  37117. }
  37118. var indices = new Array();
  37119. var positions = new Array();
  37120. var normals = new Array();
  37121. var uvs = new Array();
  37122. var colors = new Array();
  37123. var angle_step = Math.PI * 2 * arc / tessellation;
  37124. var angle;
  37125. var h;
  37126. var radius;
  37127. var tan = (diameterBottom - diameterTop) / 2 / height;
  37128. var ringVertex = BABYLON.Vector3.Zero();
  37129. var ringNormal = BABYLON.Vector3.Zero();
  37130. var ringFirstVertex = BABYLON.Vector3.Zero();
  37131. var ringFirstNormal = BABYLON.Vector3.Zero();
  37132. var quadNormal = BABYLON.Vector3.Zero();
  37133. var Y = BABYLON.Axis.Y;
  37134. // positions, normals, uvs
  37135. var i;
  37136. var j;
  37137. var r;
  37138. var ringIdx = 1;
  37139. var s = 1; // surface index
  37140. var cs = 0;
  37141. var v = 0;
  37142. for (i = 0; i <= subdivisions; i++) {
  37143. h = i / subdivisions;
  37144. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37145. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37146. for (r = 0; r < ringIdx; r++) {
  37147. if (hasRings) {
  37148. s += r;
  37149. }
  37150. if (enclose) {
  37151. s += 2 * r;
  37152. }
  37153. for (j = 0; j <= tessellation; j++) {
  37154. angle = j * angle_step;
  37155. // position
  37156. ringVertex.x = Math.cos(-angle) * radius;
  37157. ringVertex.y = -height / 2 + h * height;
  37158. ringVertex.z = Math.sin(-angle) * radius;
  37159. // normal
  37160. if (diameterTop === 0 && i === subdivisions) {
  37161. // if no top cap, reuse former normals
  37162. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37163. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37164. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37165. }
  37166. else {
  37167. ringNormal.x = ringVertex.x;
  37168. ringNormal.z = ringVertex.z;
  37169. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37170. ringNormal.normalize();
  37171. }
  37172. // keep first ring vertex values for enclose
  37173. if (j === 0) {
  37174. ringFirstVertex.copyFrom(ringVertex);
  37175. ringFirstNormal.copyFrom(ringNormal);
  37176. }
  37177. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37178. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37179. if (hasRings) {
  37180. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37181. }
  37182. else {
  37183. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37184. }
  37185. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37186. if (faceColors) {
  37187. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37188. }
  37189. }
  37190. // if enclose, add four vertices and their dedicated normals
  37191. if (arc !== 1 && enclose) {
  37192. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37193. positions.push(0, ringVertex.y, 0);
  37194. positions.push(0, ringVertex.y, 0);
  37195. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37196. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37197. quadNormal.normalize();
  37198. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37199. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37200. quadNormal.normalize();
  37201. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37202. if (hasRings) {
  37203. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37204. }
  37205. else {
  37206. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37207. }
  37208. uvs.push(faceUV[s + 1].x, v);
  37209. uvs.push(faceUV[s + 1].z, v);
  37210. if (hasRings) {
  37211. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37212. }
  37213. else {
  37214. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37215. }
  37216. uvs.push(faceUV[s + 2].x, v);
  37217. uvs.push(faceUV[s + 2].z, v);
  37218. if (faceColors) {
  37219. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37220. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37221. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37222. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37223. }
  37224. }
  37225. if (cs !== s) {
  37226. cs = s;
  37227. }
  37228. }
  37229. }
  37230. // indices
  37231. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37232. var s;
  37233. i = 0;
  37234. for (s = 0; s < subdivisions; s++) {
  37235. var i0 = 0;
  37236. var i1 = 0;
  37237. var i2 = 0;
  37238. var i3 = 0;
  37239. for (j = 0; j < tessellation; j++) {
  37240. i0 = i * (e + 1) + j;
  37241. i1 = (i + 1) * (e + 1) + j;
  37242. i2 = i * (e + 1) + (j + 1);
  37243. i3 = (i + 1) * (e + 1) + (j + 1);
  37244. indices.push(i0, i1, i2);
  37245. indices.push(i3, i2, i1);
  37246. }
  37247. if (arc !== 1 && enclose) { // if enclose, add two quads
  37248. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37249. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37250. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37251. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37252. }
  37253. i = (hasRings) ? (i + 2) : (i + 1);
  37254. }
  37255. // Caps
  37256. var createCylinderCap = function (isTop) {
  37257. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37258. if (radius === 0) {
  37259. return;
  37260. }
  37261. // Cap positions, normals & uvs
  37262. var angle;
  37263. var circleVector;
  37264. var i;
  37265. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37266. var c = null;
  37267. if (faceColors) {
  37268. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37269. }
  37270. // cap center
  37271. var vbase = positions.length / 3;
  37272. var offset = isTop ? height / 2 : -height / 2;
  37273. var center = new BABYLON.Vector3(0, offset, 0);
  37274. positions.push(center.x, center.y, center.z);
  37275. normals.push(0, isTop ? 1 : -1, 0);
  37276. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37277. if (c) {
  37278. colors.push(c.r, c.g, c.b, c.a);
  37279. }
  37280. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37281. for (i = 0; i <= tessellation; i++) {
  37282. angle = Math.PI * 2 * i * arc / tessellation;
  37283. var cos = Math.cos(-angle);
  37284. var sin = Math.sin(-angle);
  37285. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37286. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37287. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37288. normals.push(0, isTop ? 1 : -1, 0);
  37289. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37290. if (c) {
  37291. colors.push(c.r, c.g, c.b, c.a);
  37292. }
  37293. }
  37294. // Cap indices
  37295. for (i = 0; i < tessellation; i++) {
  37296. if (!isTop) {
  37297. indices.push(vbase);
  37298. indices.push(vbase + (i + 1));
  37299. indices.push(vbase + (i + 2));
  37300. }
  37301. else {
  37302. indices.push(vbase);
  37303. indices.push(vbase + (i + 2));
  37304. indices.push(vbase + (i + 1));
  37305. }
  37306. }
  37307. };
  37308. // add caps to geometry
  37309. createCylinderCap(false);
  37310. createCylinderCap(true);
  37311. // Sides
  37312. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37313. var vertexData = new VertexData();
  37314. vertexData.indices = indices;
  37315. vertexData.positions = positions;
  37316. vertexData.normals = normals;
  37317. vertexData.uvs = uvs;
  37318. if (faceColors) {
  37319. vertexData.colors = colors;
  37320. }
  37321. return vertexData;
  37322. };
  37323. /**
  37324. * Creates the VertexData for a torus
  37325. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37326. * * diameter the diameter of the torus, optional default 1
  37327. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37328. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37329. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37330. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37331. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37332. * @returns the VertexData of the torus
  37333. */
  37334. VertexData.CreateTorus = function (options) {
  37335. var indices = [];
  37336. var positions = [];
  37337. var normals = [];
  37338. var uvs = [];
  37339. var diameter = options.diameter || 1;
  37340. var thickness = options.thickness || 0.5;
  37341. var tessellation = options.tessellation || 16;
  37342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37343. var stride = tessellation + 1;
  37344. for (var i = 0; i <= tessellation; i++) {
  37345. var u = i / tessellation;
  37346. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37347. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37348. for (var j = 0; j <= tessellation; j++) {
  37349. var v = 1 - j / tessellation;
  37350. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37351. var dx = Math.cos(innerAngle);
  37352. var dy = Math.sin(innerAngle);
  37353. // Create a vertex.
  37354. var normal = new BABYLON.Vector3(dx, dy, 0);
  37355. var position = normal.scale(thickness / 2);
  37356. var textureCoordinate = new BABYLON.Vector2(u, v);
  37357. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37358. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37359. positions.push(position.x, position.y, position.z);
  37360. normals.push(normal.x, normal.y, normal.z);
  37361. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37362. // And create indices for two triangles.
  37363. var nextI = (i + 1) % stride;
  37364. var nextJ = (j + 1) % stride;
  37365. indices.push(i * stride + j);
  37366. indices.push(i * stride + nextJ);
  37367. indices.push(nextI * stride + j);
  37368. indices.push(i * stride + nextJ);
  37369. indices.push(nextI * stride + nextJ);
  37370. indices.push(nextI * stride + j);
  37371. }
  37372. }
  37373. // Sides
  37374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37375. // Result
  37376. var vertexData = new VertexData();
  37377. vertexData.indices = indices;
  37378. vertexData.positions = positions;
  37379. vertexData.normals = normals;
  37380. vertexData.uvs = uvs;
  37381. return vertexData;
  37382. };
  37383. /**
  37384. * Creates the VertexData of the LineSystem
  37385. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37386. * - lines an array of lines, each line being an array of successive Vector3
  37387. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37388. * @returns the VertexData of the LineSystem
  37389. */
  37390. VertexData.CreateLineSystem = function (options) {
  37391. var indices = [];
  37392. var positions = [];
  37393. var lines = options.lines;
  37394. var colors = options.colors;
  37395. var vertexColors = [];
  37396. var idx = 0;
  37397. for (var l = 0; l < lines.length; l++) {
  37398. var points = lines[l];
  37399. for (var index = 0; index < points.length; index++) {
  37400. positions.push(points[index].x, points[index].y, points[index].z);
  37401. if (colors) {
  37402. var color = colors[l];
  37403. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37404. }
  37405. if (index > 0) {
  37406. indices.push(idx - 1);
  37407. indices.push(idx);
  37408. }
  37409. idx++;
  37410. }
  37411. }
  37412. var vertexData = new VertexData();
  37413. vertexData.indices = indices;
  37414. vertexData.positions = positions;
  37415. if (colors) {
  37416. vertexData.colors = vertexColors;
  37417. }
  37418. return vertexData;
  37419. };
  37420. /**
  37421. * Create the VertexData for a DashedLines
  37422. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37423. * - points an array successive Vector3
  37424. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37425. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37426. * - dashNb the intended total number of dashes, optional, default 200
  37427. * @returns the VertexData for the DashedLines
  37428. */
  37429. VertexData.CreateDashedLines = function (options) {
  37430. var dashSize = options.dashSize || 3;
  37431. var gapSize = options.gapSize || 1;
  37432. var dashNb = options.dashNb || 200;
  37433. var points = options.points;
  37434. var positions = new Array();
  37435. var indices = new Array();
  37436. var curvect = BABYLON.Vector3.Zero();
  37437. var lg = 0;
  37438. var nb = 0;
  37439. var shft = 0;
  37440. var dashshft = 0;
  37441. var curshft = 0;
  37442. var idx = 0;
  37443. var i = 0;
  37444. for (i = 0; i < points.length - 1; i++) {
  37445. points[i + 1].subtractToRef(points[i], curvect);
  37446. lg += curvect.length();
  37447. }
  37448. shft = lg / dashNb;
  37449. dashshft = dashSize * shft / (dashSize + gapSize);
  37450. for (i = 0; i < points.length - 1; i++) {
  37451. points[i + 1].subtractToRef(points[i], curvect);
  37452. nb = Math.floor(curvect.length() / shft);
  37453. curvect.normalize();
  37454. for (var j = 0; j < nb; j++) {
  37455. curshft = shft * j;
  37456. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37457. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37458. indices.push(idx, idx + 1);
  37459. idx += 2;
  37460. }
  37461. }
  37462. // Result
  37463. var vertexData = new VertexData();
  37464. vertexData.positions = positions;
  37465. vertexData.indices = indices;
  37466. return vertexData;
  37467. };
  37468. /**
  37469. * Creates the VertexData for a Ground
  37470. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37471. * - width the width (x direction) of the ground, optional, default 1
  37472. * - height the height (z direction) of the ground, optional, default 1
  37473. * - subdivisions the number of subdivisions per side, optional, default 1
  37474. * @returns the VertexData of the Ground
  37475. */
  37476. VertexData.CreateGround = function (options) {
  37477. var indices = [];
  37478. var positions = [];
  37479. var normals = [];
  37480. var uvs = [];
  37481. var row, col;
  37482. var width = options.width || 1;
  37483. var height = options.height || 1;
  37484. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37485. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37486. for (row = 0; row <= subdivisionsY; row++) {
  37487. for (col = 0; col <= subdivisionsX; col++) {
  37488. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37489. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37490. positions.push(position.x, position.y, position.z);
  37491. normals.push(normal.x, normal.y, normal.z);
  37492. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37493. }
  37494. }
  37495. for (row = 0; row < subdivisionsY; row++) {
  37496. for (col = 0; col < subdivisionsX; col++) {
  37497. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37498. indices.push(col + 1 + row * (subdivisionsX + 1));
  37499. indices.push(col + row * (subdivisionsX + 1));
  37500. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37501. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37502. indices.push(col + row * (subdivisionsX + 1));
  37503. }
  37504. }
  37505. // Result
  37506. var vertexData = new VertexData();
  37507. vertexData.indices = indices;
  37508. vertexData.positions = positions;
  37509. vertexData.normals = normals;
  37510. vertexData.uvs = uvs;
  37511. return vertexData;
  37512. };
  37513. /**
  37514. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37515. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37516. * * xmin the ground minimum X coordinate, optional, default -1
  37517. * * zmin the ground minimum Z coordinate, optional, default -1
  37518. * * xmax the ground maximum X coordinate, optional, default 1
  37519. * * zmax the ground maximum Z coordinate, optional, default 1
  37520. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37521. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37522. * @returns the VertexData of the TiledGround
  37523. */
  37524. VertexData.CreateTiledGround = function (options) {
  37525. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37526. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37527. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37528. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37529. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37530. var precision = options.precision || { w: 1, h: 1 };
  37531. var indices = new Array();
  37532. var positions = new Array();
  37533. var normals = new Array();
  37534. var uvs = new Array();
  37535. var row, col, tileRow, tileCol;
  37536. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37537. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37538. precision.w = (precision.w < 1) ? 1 : precision.w;
  37539. precision.h = (precision.h < 1) ? 1 : precision.h;
  37540. var tileSize = {
  37541. 'w': (xmax - xmin) / subdivisions.w,
  37542. 'h': (zmax - zmin) / subdivisions.h
  37543. };
  37544. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37545. // Indices
  37546. var base = positions.length / 3;
  37547. var rowLength = precision.w + 1;
  37548. for (row = 0; row < precision.h; row++) {
  37549. for (col = 0; col < precision.w; col++) {
  37550. var square = [
  37551. base + col + row * rowLength,
  37552. base + (col + 1) + row * rowLength,
  37553. base + (col + 1) + (row + 1) * rowLength,
  37554. base + col + (row + 1) * rowLength
  37555. ];
  37556. indices.push(square[1]);
  37557. indices.push(square[2]);
  37558. indices.push(square[3]);
  37559. indices.push(square[0]);
  37560. indices.push(square[1]);
  37561. indices.push(square[3]);
  37562. }
  37563. }
  37564. // Position, normals and uvs
  37565. var position = BABYLON.Vector3.Zero();
  37566. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37567. for (row = 0; row <= precision.h; row++) {
  37568. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37569. for (col = 0; col <= precision.w; col++) {
  37570. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37571. position.y = 0;
  37572. positions.push(position.x, position.y, position.z);
  37573. normals.push(normal.x, normal.y, normal.z);
  37574. uvs.push(col / precision.w, row / precision.h);
  37575. }
  37576. }
  37577. }
  37578. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37579. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37580. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37581. }
  37582. }
  37583. // Result
  37584. var vertexData = new VertexData();
  37585. vertexData.indices = indices;
  37586. vertexData.positions = positions;
  37587. vertexData.normals = normals;
  37588. vertexData.uvs = uvs;
  37589. return vertexData;
  37590. };
  37591. /**
  37592. * Creates the VertexData of the Ground designed from a heightmap
  37593. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37594. * * width the width (x direction) of the ground
  37595. * * height the height (z direction) of the ground
  37596. * * subdivisions the number of subdivisions per side
  37597. * * minHeight the minimum altitude on the ground, optional, default 0
  37598. * * maxHeight the maximum altitude on the ground, optional default 1
  37599. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37600. * * buffer the array holding the image color data
  37601. * * bufferWidth the width of image
  37602. * * bufferHeight the height of image
  37603. * @returns the VertexData of the Ground designed from a heightmap
  37604. */
  37605. VertexData.CreateGroundFromHeightMap = function (options) {
  37606. var indices = [];
  37607. var positions = [];
  37608. var normals = [];
  37609. var uvs = [];
  37610. var row, col;
  37611. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37612. // Vertices
  37613. for (row = 0; row <= options.subdivisions; row++) {
  37614. for (col = 0; col <= options.subdivisions; col++) {
  37615. 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));
  37616. // Compute height
  37617. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37618. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37619. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37620. var r = options.buffer[pos] / 255.0;
  37621. var g = options.buffer[pos + 1] / 255.0;
  37622. var b = options.buffer[pos + 2] / 255.0;
  37623. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37624. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37625. // Add vertex
  37626. positions.push(position.x, position.y, position.z);
  37627. normals.push(0, 0, 0);
  37628. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37629. }
  37630. }
  37631. // Indices
  37632. for (row = 0; row < options.subdivisions; row++) {
  37633. for (col = 0; col < options.subdivisions; col++) {
  37634. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37635. indices.push(col + 1 + row * (options.subdivisions + 1));
  37636. indices.push(col + row * (options.subdivisions + 1));
  37637. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37638. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37639. indices.push(col + row * (options.subdivisions + 1));
  37640. }
  37641. }
  37642. // Normals
  37643. VertexData.ComputeNormals(positions, indices, normals);
  37644. // Result
  37645. var vertexData = new VertexData();
  37646. vertexData.indices = indices;
  37647. vertexData.positions = positions;
  37648. vertexData.normals = normals;
  37649. vertexData.uvs = uvs;
  37650. return vertexData;
  37651. };
  37652. /**
  37653. * Creates the VertexData for a Plane
  37654. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37655. * * size sets the width and height of the plane to the value of size, optional default 1
  37656. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37657. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37658. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37659. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37660. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37661. * @returns the VertexData of the box
  37662. */
  37663. VertexData.CreatePlane = function (options) {
  37664. var indices = [];
  37665. var positions = [];
  37666. var normals = [];
  37667. var uvs = [];
  37668. var width = options.width || options.size || 1;
  37669. var height = options.height || options.size || 1;
  37670. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37671. // Vertices
  37672. var halfWidth = width / 2.0;
  37673. var halfHeight = height / 2.0;
  37674. positions.push(-halfWidth, -halfHeight, 0);
  37675. normals.push(0, 0, -1.0);
  37676. uvs.push(0.0, 0.0);
  37677. positions.push(halfWidth, -halfHeight, 0);
  37678. normals.push(0, 0, -1.0);
  37679. uvs.push(1.0, 0.0);
  37680. positions.push(halfWidth, halfHeight, 0);
  37681. normals.push(0, 0, -1.0);
  37682. uvs.push(1.0, 1.0);
  37683. positions.push(-halfWidth, halfHeight, 0);
  37684. normals.push(0, 0, -1.0);
  37685. uvs.push(0.0, 1.0);
  37686. // Indices
  37687. indices.push(0);
  37688. indices.push(1);
  37689. indices.push(2);
  37690. indices.push(0);
  37691. indices.push(2);
  37692. indices.push(3);
  37693. // Sides
  37694. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37695. // Result
  37696. var vertexData = new VertexData();
  37697. vertexData.indices = indices;
  37698. vertexData.positions = positions;
  37699. vertexData.normals = normals;
  37700. vertexData.uvs = uvs;
  37701. return vertexData;
  37702. };
  37703. /**
  37704. * Creates the VertexData of the Disc or regular Polygon
  37705. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37706. * * radius the radius of the disc, optional default 0.5
  37707. * * tessellation the number of polygon sides, optional, default 64
  37708. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37709. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37710. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37711. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37712. * @returns the VertexData of the box
  37713. */
  37714. VertexData.CreateDisc = function (options) {
  37715. var positions = new Array();
  37716. var indices = new Array();
  37717. var normals = new Array();
  37718. var uvs = new Array();
  37719. var radius = options.radius || 0.5;
  37720. var tessellation = options.tessellation || 64;
  37721. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37722. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37723. // positions and uvs
  37724. positions.push(0, 0, 0); // disc center first
  37725. uvs.push(0.5, 0.5);
  37726. var theta = Math.PI * 2 * arc;
  37727. var step = theta / tessellation;
  37728. for (var a = 0; a < theta; a += step) {
  37729. var x = Math.cos(a);
  37730. var y = Math.sin(a);
  37731. var u = (x + 1) / 2;
  37732. var v = (1 - y) / 2;
  37733. positions.push(radius * x, radius * y, 0);
  37734. uvs.push(u, v);
  37735. }
  37736. if (arc === 1) {
  37737. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37738. uvs.push(uvs[2], uvs[3]);
  37739. }
  37740. //indices
  37741. var vertexNb = positions.length / 3;
  37742. for (var i = 1; i < vertexNb - 1; i++) {
  37743. indices.push(i + 1, 0, i);
  37744. }
  37745. // result
  37746. VertexData.ComputeNormals(positions, indices, normals);
  37747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37748. var vertexData = new VertexData();
  37749. vertexData.indices = indices;
  37750. vertexData.positions = positions;
  37751. vertexData.normals = normals;
  37752. vertexData.uvs = uvs;
  37753. return vertexData;
  37754. };
  37755. /**
  37756. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37757. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37758. * @param polygon a mesh built from polygonTriangulation.build()
  37759. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37760. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37761. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37762. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37763. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37764. * @returns the VertexData of the Polygon
  37765. */
  37766. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37767. var faceUV = fUV || new Array(3);
  37768. var faceColors = fColors;
  37769. var colors = [];
  37770. // default face colors and UV if undefined
  37771. for (var f = 0; f < 3; f++) {
  37772. if (faceUV[f] === undefined) {
  37773. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37774. }
  37775. if (faceColors && faceColors[f] === undefined) {
  37776. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37777. }
  37778. }
  37779. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37780. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37781. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37782. var indices = polygon.getIndices();
  37783. // set face colours and textures
  37784. var idx = 0;
  37785. var face = 0;
  37786. for (var index = 0; index < normals.length; index += 3) {
  37787. //Edge Face no. 1
  37788. if (Math.abs(normals[index + 1]) < 0.001) {
  37789. face = 1;
  37790. }
  37791. //Top Face no. 0
  37792. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37793. face = 0;
  37794. }
  37795. //Bottom Face no. 2
  37796. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37797. face = 2;
  37798. }
  37799. idx = index / 3;
  37800. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37801. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37802. if (faceColors) {
  37803. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37804. }
  37805. }
  37806. // sides
  37807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37808. // Result
  37809. var vertexData = new VertexData();
  37810. vertexData.indices = indices;
  37811. vertexData.positions = positions;
  37812. vertexData.normals = normals;
  37813. vertexData.uvs = uvs;
  37814. if (faceColors) {
  37815. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37816. vertexData.colors = totalColors;
  37817. }
  37818. return vertexData;
  37819. };
  37820. /**
  37821. * Creates the VertexData of the IcoSphere
  37822. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37823. * * radius the radius of the IcoSphere, optional default 1
  37824. * * radiusX allows stretching in the x direction, optional, default radius
  37825. * * radiusY allows stretching in the y direction, optional, default radius
  37826. * * radiusZ allows stretching in the z direction, optional, default radius
  37827. * * flat when true creates a flat shaded mesh, optional, default true
  37828. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37829. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37830. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37831. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37832. * @returns the VertexData of the IcoSphere
  37833. */
  37834. VertexData.CreateIcoSphere = function (options) {
  37835. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37836. var radius = options.radius || 1;
  37837. var flat = (options.flat === undefined) ? true : options.flat;
  37838. var subdivisions = options.subdivisions || 4;
  37839. var radiusX = options.radiusX || radius;
  37840. var radiusY = options.radiusY || radius;
  37841. var radiusZ = options.radiusZ || radius;
  37842. var t = (1 + Math.sqrt(5)) / 2;
  37843. // 12 vertex x,y,z
  37844. var ico_vertices = [
  37845. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37846. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37847. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37848. ];
  37849. // index of 3 vertex makes a face of icopshere
  37850. var ico_indices = [
  37851. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37852. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37853. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37854. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37855. ];
  37856. // vertex for uv have aliased position, not for UV
  37857. var vertices_unalias_id = [
  37858. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37859. // vertex alias
  37860. 0,
  37861. 2,
  37862. 3,
  37863. 3,
  37864. 3,
  37865. 4,
  37866. 7,
  37867. 8,
  37868. 9,
  37869. 9,
  37870. 10,
  37871. 11 // 23: B + 12
  37872. ];
  37873. // uv as integer step (not pixels !)
  37874. var ico_vertexuv = [
  37875. 5, 1, 3, 1, 6, 4, 0, 0,
  37876. 5, 3, 4, 2, 2, 2, 4, 0,
  37877. 2, 0, 1, 1, 6, 0, 6, 2,
  37878. // vertex alias (for same vertex on different faces)
  37879. 0, 4,
  37880. 3, 3,
  37881. 4, 4,
  37882. 3, 1,
  37883. 4, 2,
  37884. 4, 4,
  37885. 0, 2,
  37886. 1, 1,
  37887. 2, 2,
  37888. 3, 3,
  37889. 1, 3,
  37890. 2, 4 // 23: B + 12
  37891. ];
  37892. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37893. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37894. // First island of uv mapping
  37895. // v = 4h 3+ 2
  37896. // v = 3h 9+ 4
  37897. // v = 2h 9+ 5 B
  37898. // v = 1h 9 1 0
  37899. // v = 0h 3 8 7 A
  37900. // u = 0 1 2 3 4 5 6 *a
  37901. // Second island of uv mapping
  37902. // v = 4h 0+ B+ 4+
  37903. // v = 3h A+ 2+
  37904. // v = 2h 7+ 6 3+
  37905. // v = 1h 8+ 3+
  37906. // v = 0h
  37907. // u = 0 1 2 3 4 5 6 *a
  37908. // Face layout on texture UV mapping
  37909. // ============
  37910. // \ 4 /\ 16 / ======
  37911. // \ / \ / /\ 11 /
  37912. // \/ 7 \/ / \ /
  37913. // ======= / 10 \/
  37914. // /\ 17 /\ =======
  37915. // / \ / \ \ 15 /\
  37916. // / 8 \/ 12 \ \ / \
  37917. // ============ \/ 6 \
  37918. // \ 18 /\ ============
  37919. // \ / \ \ 5 /\ 0 /
  37920. // \/ 13 \ \ / \ /
  37921. // ======= \/ 1 \/
  37922. // =============
  37923. // /\ 19 /\ 2 /\
  37924. // / \ / \ / \
  37925. // / 14 \/ 9 \/ 3 \
  37926. // ===================
  37927. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37928. var ustep = 138 / 1024;
  37929. var vstep = 239 / 1024;
  37930. var uoffset = 60 / 1024;
  37931. var voffset = 26 / 1024;
  37932. // Second island should have margin, not to touch the first island
  37933. // avoid any borderline artefact in pixel rounding
  37934. var island_u_offset = -40 / 1024;
  37935. var island_v_offset = +20 / 1024;
  37936. // face is either island 0 or 1 :
  37937. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37938. var island = [
  37939. 0, 0, 0, 0, 1,
  37940. 0, 0, 1, 1, 0,
  37941. 0, 0, 1, 1, 0,
  37942. 0, 1, 1, 1, 0 // 15 - 19
  37943. ];
  37944. var indices = new Array();
  37945. var positions = new Array();
  37946. var normals = new Array();
  37947. var uvs = new Array();
  37948. var current_indice = 0;
  37949. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37950. var face_vertex_pos = new Array(3);
  37951. var face_vertex_uv = new Array(3);
  37952. var v012;
  37953. for (v012 = 0; v012 < 3; v012++) {
  37954. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37955. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37956. }
  37957. // create all with normals
  37958. for (var face = 0; face < 20; face++) {
  37959. // 3 vertex per face
  37960. for (v012 = 0; v012 < 3; v012++) {
  37961. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37962. var v_id = ico_indices[3 * face + v012];
  37963. // vertex have 3D position (x,y,z)
  37964. 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]);
  37965. // Normalize to get normal, then scale to radius
  37966. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37967. // uv Coordinates from vertex ID
  37968. 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);
  37969. }
  37970. // Subdivide the face (interpolate pos, norm, uv)
  37971. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37972. // - norm is linear interpolation of vertex corner normal
  37973. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37974. // - uv is linear interpolation
  37975. //
  37976. // Topology is as below for sub-divide by 2
  37977. // vertex shown as v0,v1,v2
  37978. // interp index is i1 to progress in range [v0,v1[
  37979. // interp index is i2 to progress in range [v0,v2[
  37980. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37981. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37982. //
  37983. //
  37984. // i2 v2
  37985. // ^ ^
  37986. // / / \
  37987. // / / \
  37988. // / / \
  37989. // / / (0,1) \
  37990. // / #---------\
  37991. // / / \ (0,0)'/ \
  37992. // / / \ / \
  37993. // / / \ / \
  37994. // / / (0,0) \ / (1,0) \
  37995. // / #---------#---------\
  37996. // v0 v1
  37997. //
  37998. // --------------------> i1
  37999. //
  38000. // interp of (i1,i2):
  38001. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38002. // along i1 : lerp(x0,x1, i1/(S-i2))
  38003. //
  38004. // centroid of triangle is needed to get help normal computation
  38005. // (c1,c2) are used for centroid location
  38006. var interp_vertex = function (i1, i2, c1, c2) {
  38007. // vertex is interpolated from
  38008. // - face_vertex_pos[0..2]
  38009. // - face_vertex_uv[0..2]
  38010. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38011. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38012. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38013. pos_interp.normalize();
  38014. var vertex_normal;
  38015. if (flat) {
  38016. // in flat mode, recalculate normal as face centroid normal
  38017. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38018. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38019. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38020. }
  38021. else {
  38022. // in smooth mode, recalculate normal from each single vertex position
  38023. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38024. }
  38025. // Vertex normal need correction due to X,Y,Z radius scaling
  38026. vertex_normal.x /= radiusX;
  38027. vertex_normal.y /= radiusY;
  38028. vertex_normal.z /= radiusZ;
  38029. vertex_normal.normalize();
  38030. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38031. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38032. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38033. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38034. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38035. uvs.push(uv_interp.x, uv_interp.y);
  38036. // push each vertex has member of a face
  38037. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38038. indices.push(current_indice);
  38039. current_indice++;
  38040. };
  38041. for (var i2 = 0; i2 < subdivisions; i2++) {
  38042. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38043. // face : (i1,i2) for /\ :
  38044. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38045. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38046. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38047. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38048. if (i1 + i2 + 1 < subdivisions) {
  38049. // face : (i1,i2)' for \/ :
  38050. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38051. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38052. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38053. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38054. }
  38055. }
  38056. }
  38057. }
  38058. // Sides
  38059. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38060. // Result
  38061. var vertexData = new VertexData();
  38062. vertexData.indices = indices;
  38063. vertexData.positions = positions;
  38064. vertexData.normals = normals;
  38065. vertexData.uvs = uvs;
  38066. return vertexData;
  38067. };
  38068. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38069. /**
  38070. * Creates the VertexData for a Polyhedron
  38071. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38072. * * type provided types are:
  38073. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38074. * * 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)
  38075. * * size the size of the IcoSphere, optional default 1
  38076. * * sizeX allows stretching in the x direction, optional, default size
  38077. * * sizeY allows stretching in the y direction, optional, default size
  38078. * * sizeZ allows stretching in the z direction, optional, default size
  38079. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38080. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38081. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38082. * * flat when true creates a flat shaded mesh, optional, default true
  38083. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38084. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38085. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38086. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38087. * @returns the VertexData of the Polyhedron
  38088. */
  38089. VertexData.CreatePolyhedron = function (options) {
  38090. // provided polyhedron types :
  38091. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38092. // 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)
  38093. var polyhedra = [];
  38094. 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]] };
  38095. 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]] };
  38096. polyhedra[2] = {
  38097. 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]],
  38098. 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]]
  38099. };
  38100. polyhedra[3] = {
  38101. 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]],
  38102. 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]]
  38103. };
  38104. polyhedra[4] = {
  38105. 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]],
  38106. 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]]
  38107. };
  38108. 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]] };
  38109. 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]] };
  38110. 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]] };
  38111. 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]] };
  38112. 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]] };
  38113. 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]] };
  38114. 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]] };
  38115. 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]] };
  38116. 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]] };
  38117. polyhedra[14] = {
  38118. 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]],
  38119. 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]]
  38120. };
  38121. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38122. var size = options.size;
  38123. var sizeX = options.sizeX || size || 1;
  38124. var sizeY = options.sizeY || size || 1;
  38125. var sizeZ = options.sizeZ || size || 1;
  38126. var data = options.custom || polyhedra[type];
  38127. var nbfaces = data.face.length;
  38128. var faceUV = options.faceUV || new Array(nbfaces);
  38129. var faceColors = options.faceColors;
  38130. var flat = (options.flat === undefined) ? true : options.flat;
  38131. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38132. var positions = new Array();
  38133. var indices = new Array();
  38134. var normals = new Array();
  38135. var uvs = new Array();
  38136. var colors = new Array();
  38137. var index = 0;
  38138. var faceIdx = 0; // face cursor in the array "indexes"
  38139. var indexes = new Array();
  38140. var i = 0;
  38141. var f = 0;
  38142. var u, v, ang, x, y, tmp;
  38143. // default face colors and UV if undefined
  38144. if (flat) {
  38145. for (f = 0; f < nbfaces; f++) {
  38146. if (faceColors && faceColors[f] === undefined) {
  38147. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38148. }
  38149. if (faceUV && faceUV[f] === undefined) {
  38150. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38151. }
  38152. }
  38153. }
  38154. if (!flat) {
  38155. for (i = 0; i < data.vertex.length; i++) {
  38156. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38157. uvs.push(0, 0);
  38158. }
  38159. for (f = 0; f < nbfaces; f++) {
  38160. for (i = 0; i < data.face[f].length - 2; i++) {
  38161. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38162. }
  38163. }
  38164. }
  38165. else {
  38166. for (f = 0; f < nbfaces; f++) {
  38167. var fl = data.face[f].length; // number of vertices of the current face
  38168. ang = 2 * Math.PI / fl;
  38169. x = 0.5 * Math.tan(ang / 2);
  38170. y = 0.5;
  38171. // positions, uvs, colors
  38172. for (i = 0; i < fl; i++) {
  38173. // positions
  38174. 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);
  38175. indexes.push(index);
  38176. index++;
  38177. // uvs
  38178. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38179. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38180. uvs.push(u, v);
  38181. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38182. y = x * Math.sin(ang) + y * Math.cos(ang);
  38183. x = tmp;
  38184. // colors
  38185. if (faceColors) {
  38186. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38187. }
  38188. }
  38189. // indices from indexes
  38190. for (i = 0; i < fl - 2; i++) {
  38191. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38192. }
  38193. faceIdx += fl;
  38194. }
  38195. }
  38196. VertexData.ComputeNormals(positions, indices, normals);
  38197. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38198. var vertexData = new VertexData();
  38199. vertexData.positions = positions;
  38200. vertexData.indices = indices;
  38201. vertexData.normals = normals;
  38202. vertexData.uvs = uvs;
  38203. if (faceColors && flat) {
  38204. vertexData.colors = colors;
  38205. }
  38206. return vertexData;
  38207. };
  38208. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38209. /**
  38210. * Creates the VertexData for a TorusKnot
  38211. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38212. * * radius the radius of the torus knot, optional, default 2
  38213. * * tube the thickness of the tube, optional, default 0.5
  38214. * * radialSegments the number of sides on each tube segments, optional, default 32
  38215. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38216. * * p the number of windings around the z axis, optional, default 2
  38217. * * q the number of windings around the x axis, optional, default 3
  38218. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38219. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38220. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38221. * @returns the VertexData of the Torus Knot
  38222. */
  38223. VertexData.CreateTorusKnot = function (options) {
  38224. var indices = new Array();
  38225. var positions = new Array();
  38226. var normals = new Array();
  38227. var uvs = new Array();
  38228. var radius = options.radius || 2;
  38229. var tube = options.tube || 0.5;
  38230. var radialSegments = options.radialSegments || 32;
  38231. var tubularSegments = options.tubularSegments || 32;
  38232. var p = options.p || 2;
  38233. var q = options.q || 3;
  38234. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38235. // Helper
  38236. var getPos = function (angle) {
  38237. var cu = Math.cos(angle);
  38238. var su = Math.sin(angle);
  38239. var quOverP = q / p * angle;
  38240. var cs = Math.cos(quOverP);
  38241. var tx = radius * (2 + cs) * 0.5 * cu;
  38242. var ty = radius * (2 + cs) * su * 0.5;
  38243. var tz = radius * Math.sin(quOverP) * 0.5;
  38244. return new BABYLON.Vector3(tx, ty, tz);
  38245. };
  38246. // Vertices
  38247. var i;
  38248. var j;
  38249. for (i = 0; i <= radialSegments; i++) {
  38250. var modI = i % radialSegments;
  38251. var u = modI / radialSegments * 2 * p * Math.PI;
  38252. var p1 = getPos(u);
  38253. var p2 = getPos(u + 0.01);
  38254. var tang = p2.subtract(p1);
  38255. var n = p2.add(p1);
  38256. var bitan = BABYLON.Vector3.Cross(tang, n);
  38257. n = BABYLON.Vector3.Cross(bitan, tang);
  38258. bitan.normalize();
  38259. n.normalize();
  38260. for (j = 0; j < tubularSegments; j++) {
  38261. var modJ = j % tubularSegments;
  38262. var v = modJ / tubularSegments * 2 * Math.PI;
  38263. var cx = -tube * Math.cos(v);
  38264. var cy = tube * Math.sin(v);
  38265. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38266. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38267. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38268. uvs.push(i / radialSegments);
  38269. uvs.push(j / tubularSegments);
  38270. }
  38271. }
  38272. for (i = 0; i < radialSegments; i++) {
  38273. for (j = 0; j < tubularSegments; j++) {
  38274. var jNext = (j + 1) % tubularSegments;
  38275. var a = i * tubularSegments + j;
  38276. var b = (i + 1) * tubularSegments + j;
  38277. var c = (i + 1) * tubularSegments + jNext;
  38278. var d = i * tubularSegments + jNext;
  38279. indices.push(d);
  38280. indices.push(b);
  38281. indices.push(a);
  38282. indices.push(d);
  38283. indices.push(c);
  38284. indices.push(b);
  38285. }
  38286. }
  38287. // Normals
  38288. VertexData.ComputeNormals(positions, indices, normals);
  38289. // Sides
  38290. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38291. // Result
  38292. var vertexData = new VertexData();
  38293. vertexData.indices = indices;
  38294. vertexData.positions = positions;
  38295. vertexData.normals = normals;
  38296. vertexData.uvs = uvs;
  38297. return vertexData;
  38298. };
  38299. // Tools
  38300. /**
  38301. * Compute normals for given positions and indices
  38302. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38303. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38304. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38305. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38306. * * facetNormals : optional array of facet normals (vector3)
  38307. * * facetPositions : optional array of facet positions (vector3)
  38308. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38309. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38310. * * bInfo : optional bounding info, required for facetPartitioning computation
  38311. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38312. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38313. * * useRightHandedSystem: optional boolean to for right handed system computation
  38314. * * depthSort : optional boolean to enable the facet depth sort computation
  38315. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38316. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38317. */
  38318. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38319. // temporary scalar variables
  38320. var index = 0; // facet index
  38321. var p1p2x = 0.0; // p1p2 vector x coordinate
  38322. var p1p2y = 0.0; // p1p2 vector y coordinate
  38323. var p1p2z = 0.0; // p1p2 vector z coordinate
  38324. var p3p2x = 0.0; // p3p2 vector x coordinate
  38325. var p3p2y = 0.0; // p3p2 vector y coordinate
  38326. var p3p2z = 0.0; // p3p2 vector z coordinate
  38327. var faceNormalx = 0.0; // facet normal x coordinate
  38328. var faceNormaly = 0.0; // facet normal y coordinate
  38329. var faceNormalz = 0.0; // facet normal z coordinate
  38330. var length = 0.0; // facet normal length before normalization
  38331. var v1x = 0; // vector1 x index in the positions array
  38332. var v1y = 0; // vector1 y index in the positions array
  38333. var v1z = 0; // vector1 z index in the positions array
  38334. var v2x = 0; // vector2 x index in the positions array
  38335. var v2y = 0; // vector2 y index in the positions array
  38336. var v2z = 0; // vector2 z index in the positions array
  38337. var v3x = 0; // vector3 x index in the positions array
  38338. var v3y = 0; // vector3 y index in the positions array
  38339. var v3z = 0; // vector3 z index in the positions array
  38340. var computeFacetNormals = false;
  38341. var computeFacetPositions = false;
  38342. var computeFacetPartitioning = false;
  38343. var computeDepthSort = false;
  38344. var faceNormalSign = 1;
  38345. var ratio = 0;
  38346. var distanceTo = null;
  38347. if (options) {
  38348. computeFacetNormals = (options.facetNormals) ? true : false;
  38349. computeFacetPositions = (options.facetPositions) ? true : false;
  38350. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38351. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38352. ratio = options.ratio || 0;
  38353. computeDepthSort = (options.depthSort) ? true : false;
  38354. distanceTo = (options.distanceTo);
  38355. if (computeDepthSort) {
  38356. if (distanceTo === undefined) {
  38357. distanceTo = BABYLON.Vector3.Zero();
  38358. }
  38359. var depthSortedFacets = options.depthSortedFacets;
  38360. }
  38361. }
  38362. // facetPartitioning reinit if needed
  38363. var xSubRatio = 0;
  38364. var ySubRatio = 0;
  38365. var zSubRatio = 0;
  38366. var subSq = 0;
  38367. if (computeFacetPartitioning && options && options.bbSize) {
  38368. var ox = 0; // X partitioning index for facet position
  38369. var oy = 0; // Y partinioning index for facet position
  38370. var oz = 0; // Z partinioning index for facet position
  38371. var b1x = 0; // X partitioning index for facet v1 vertex
  38372. var b1y = 0; // Y partitioning index for facet v1 vertex
  38373. var b1z = 0; // z partitioning index for facet v1 vertex
  38374. var b2x = 0; // X partitioning index for facet v2 vertex
  38375. var b2y = 0; // Y partitioning index for facet v2 vertex
  38376. var b2z = 0; // Z partitioning index for facet v2 vertex
  38377. var b3x = 0; // X partitioning index for facet v3 vertex
  38378. var b3y = 0; // Y partitioning index for facet v3 vertex
  38379. var b3z = 0; // Z partitioning index for facet v3 vertex
  38380. var block_idx_o = 0; // facet barycenter block index
  38381. var block_idx_v1 = 0; // v1 vertex block index
  38382. var block_idx_v2 = 0; // v2 vertex block index
  38383. var block_idx_v3 = 0; // v3 vertex block index
  38384. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38385. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38386. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38387. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38388. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38389. subSq = options.subDiv.max * options.subDiv.max;
  38390. options.facetPartitioning.length = 0;
  38391. }
  38392. // reset the normals
  38393. for (index = 0; index < positions.length; index++) {
  38394. normals[index] = 0.0;
  38395. }
  38396. // Loop : 1 indice triplet = 1 facet
  38397. var nbFaces = (indices.length / 3) | 0;
  38398. for (index = 0; index < nbFaces; index++) {
  38399. // get the indexes of the coordinates of each vertex of the facet
  38400. v1x = indices[index * 3] * 3;
  38401. v1y = v1x + 1;
  38402. v1z = v1x + 2;
  38403. v2x = indices[index * 3 + 1] * 3;
  38404. v2y = v2x + 1;
  38405. v2z = v2x + 2;
  38406. v3x = indices[index * 3 + 2] * 3;
  38407. v3y = v3x + 1;
  38408. v3z = v3x + 2;
  38409. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38410. p1p2y = positions[v1y] - positions[v2y];
  38411. p1p2z = positions[v1z] - positions[v2z];
  38412. p3p2x = positions[v3x] - positions[v2x];
  38413. p3p2y = positions[v3y] - positions[v2y];
  38414. p3p2z = positions[v3z] - positions[v2z];
  38415. // compute the face normal with the cross product
  38416. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38417. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38418. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38419. // normalize this normal and store it in the array facetData
  38420. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38421. length = (length === 0) ? 1.0 : length;
  38422. faceNormalx /= length;
  38423. faceNormaly /= length;
  38424. faceNormalz /= length;
  38425. if (computeFacetNormals && options) {
  38426. options.facetNormals[index].x = faceNormalx;
  38427. options.facetNormals[index].y = faceNormaly;
  38428. options.facetNormals[index].z = faceNormalz;
  38429. }
  38430. if (computeFacetPositions && options) {
  38431. // compute and the facet barycenter coordinates in the array facetPositions
  38432. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38433. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38434. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38435. }
  38436. if (computeFacetPartitioning && options) {
  38437. // store the facet indexes in arrays in the main facetPartitioning array :
  38438. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38439. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38440. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38441. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38442. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38443. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38444. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38445. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38446. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38447. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38448. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38449. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38450. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38451. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38452. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38453. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38454. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38455. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38456. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38457. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38458. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38459. // push each facet index in each block containing the vertex
  38460. options.facetPartitioning[block_idx_v1].push(index);
  38461. if (block_idx_v2 != block_idx_v1) {
  38462. options.facetPartitioning[block_idx_v2].push(index);
  38463. }
  38464. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38465. options.facetPartitioning[block_idx_v3].push(index);
  38466. }
  38467. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38468. options.facetPartitioning[block_idx_o].push(index);
  38469. }
  38470. }
  38471. if (computeDepthSort && options && options.facetPositions) {
  38472. var dsf = depthSortedFacets[index];
  38473. dsf.ind = index * 3;
  38474. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38475. }
  38476. // compute the normals anyway
  38477. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38478. normals[v1y] += faceNormaly;
  38479. normals[v1z] += faceNormalz;
  38480. normals[v2x] += faceNormalx;
  38481. normals[v2y] += faceNormaly;
  38482. normals[v2z] += faceNormalz;
  38483. normals[v3x] += faceNormalx;
  38484. normals[v3y] += faceNormaly;
  38485. normals[v3z] += faceNormalz;
  38486. }
  38487. // last normalization of each normal
  38488. for (index = 0; index < normals.length / 3; index++) {
  38489. faceNormalx = normals[index * 3];
  38490. faceNormaly = normals[index * 3 + 1];
  38491. faceNormalz = normals[index * 3 + 2];
  38492. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38493. length = (length === 0) ? 1.0 : length;
  38494. faceNormalx /= length;
  38495. faceNormaly /= length;
  38496. faceNormalz /= length;
  38497. normals[index * 3] = faceNormalx;
  38498. normals[index * 3 + 1] = faceNormaly;
  38499. normals[index * 3 + 2] = faceNormalz;
  38500. }
  38501. };
  38502. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38503. var li = indices.length;
  38504. var ln = normals.length;
  38505. var i;
  38506. var n;
  38507. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38508. switch (sideOrientation) {
  38509. case BABYLON.Mesh.FRONTSIDE:
  38510. // nothing changed
  38511. break;
  38512. case BABYLON.Mesh.BACKSIDE:
  38513. var tmp;
  38514. // indices
  38515. for (i = 0; i < li; i += 3) {
  38516. tmp = indices[i];
  38517. indices[i] = indices[i + 2];
  38518. indices[i + 2] = tmp;
  38519. }
  38520. // normals
  38521. for (n = 0; n < ln; n++) {
  38522. normals[n] = -normals[n];
  38523. }
  38524. break;
  38525. case BABYLON.Mesh.DOUBLESIDE:
  38526. // positions
  38527. var lp = positions.length;
  38528. var l = lp / 3;
  38529. for (var p = 0; p < lp; p++) {
  38530. positions[lp + p] = positions[p];
  38531. }
  38532. // indices
  38533. for (i = 0; i < li; i += 3) {
  38534. indices[i + li] = indices[i + 2] + l;
  38535. indices[i + 1 + li] = indices[i + 1] + l;
  38536. indices[i + 2 + li] = indices[i] + l;
  38537. }
  38538. // normals
  38539. for (n = 0; n < ln; n++) {
  38540. normals[ln + n] = -normals[n];
  38541. }
  38542. // uvs
  38543. var lu = uvs.length;
  38544. var u = 0;
  38545. for (u = 0; u < lu; u++) {
  38546. uvs[u + lu] = uvs[u];
  38547. }
  38548. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38549. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38550. u = 0;
  38551. for (i = 0; i < lu / 2; i++) {
  38552. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38553. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38554. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38555. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38556. u += 2;
  38557. }
  38558. break;
  38559. }
  38560. };
  38561. /**
  38562. * Applies VertexData created from the imported parameters to the geometry
  38563. * @param parsedVertexData the parsed data from an imported file
  38564. * @param geometry the geometry to apply the VertexData to
  38565. */
  38566. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38567. var vertexData = new VertexData();
  38568. // positions
  38569. var positions = parsedVertexData.positions;
  38570. if (positions) {
  38571. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38572. }
  38573. // normals
  38574. var normals = parsedVertexData.normals;
  38575. if (normals) {
  38576. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38577. }
  38578. // tangents
  38579. var tangents = parsedVertexData.tangents;
  38580. if (tangents) {
  38581. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38582. }
  38583. // uvs
  38584. var uvs = parsedVertexData.uvs;
  38585. if (uvs) {
  38586. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38587. }
  38588. // uv2s
  38589. var uv2s = parsedVertexData.uv2s;
  38590. if (uv2s) {
  38591. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38592. }
  38593. // uv3s
  38594. var uv3s = parsedVertexData.uv3s;
  38595. if (uv3s) {
  38596. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38597. }
  38598. // uv4s
  38599. var uv4s = parsedVertexData.uv4s;
  38600. if (uv4s) {
  38601. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38602. }
  38603. // uv5s
  38604. var uv5s = parsedVertexData.uv5s;
  38605. if (uv5s) {
  38606. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38607. }
  38608. // uv6s
  38609. var uv6s = parsedVertexData.uv6s;
  38610. if (uv6s) {
  38611. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38612. }
  38613. // colors
  38614. var colors = parsedVertexData.colors;
  38615. if (colors) {
  38616. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38617. }
  38618. // matricesIndices
  38619. var matricesIndices = parsedVertexData.matricesIndices;
  38620. if (matricesIndices) {
  38621. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38622. }
  38623. // matricesWeights
  38624. var matricesWeights = parsedVertexData.matricesWeights;
  38625. if (matricesWeights) {
  38626. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38627. }
  38628. // indices
  38629. var indices = parsedVertexData.indices;
  38630. if (indices) {
  38631. vertexData.indices = indices;
  38632. }
  38633. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38634. };
  38635. return VertexData;
  38636. }());
  38637. BABYLON.VertexData = VertexData;
  38638. })(BABYLON || (BABYLON = {}));
  38639. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38640. var BABYLON;
  38641. (function (BABYLON) {
  38642. /**
  38643. * Class used to store geometry data (vertex buffers + index buffer)
  38644. */
  38645. var Geometry = /** @class */ (function () {
  38646. /**
  38647. * Creates a new geometry
  38648. * @param id defines the unique ID
  38649. * @param scene defines the hosting scene
  38650. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38651. * @param updatable defines if geometry must be updatable (false by default)
  38652. * @param mesh defines the mesh that will be associated with the geometry
  38653. */
  38654. function Geometry(id, scene, vertexData, updatable, mesh) {
  38655. if (updatable === void 0) { updatable = false; }
  38656. if (mesh === void 0) { mesh = null; }
  38657. /**
  38658. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38659. */
  38660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38661. this._totalVertices = 0;
  38662. this._isDisposed = false;
  38663. this._indexBufferIsUpdatable = false;
  38664. this.id = id;
  38665. this._engine = scene.getEngine();
  38666. this._meshes = [];
  38667. this._scene = scene;
  38668. //Init vertex buffer cache
  38669. this._vertexBuffers = {};
  38670. this._indices = [];
  38671. this._updatable = updatable;
  38672. // vertexData
  38673. if (vertexData) {
  38674. this.setAllVerticesData(vertexData, updatable);
  38675. }
  38676. else {
  38677. this._totalVertices = 0;
  38678. this._indices = [];
  38679. }
  38680. if (this._engine.getCaps().vertexArrayObject) {
  38681. this._vertexArrayObjects = {};
  38682. }
  38683. // applyToMesh
  38684. if (mesh) {
  38685. if (mesh.getClassName() === "LinesMesh") {
  38686. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38687. this._updateExtend();
  38688. }
  38689. this.applyToMesh(mesh);
  38690. mesh.computeWorldMatrix(true);
  38691. }
  38692. }
  38693. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38694. /**
  38695. * 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
  38696. */
  38697. get: function () {
  38698. return this._boundingBias;
  38699. },
  38700. /**
  38701. * 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
  38702. */
  38703. set: function (value) {
  38704. if (this._boundingBias && this._boundingBias.equals(value)) {
  38705. return;
  38706. }
  38707. this._boundingBias = value.clone();
  38708. this._updateBoundingInfo(true, null);
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. /**
  38714. * Static function used to attach a new empty geometry to a mesh
  38715. * @param mesh defines the mesh to attach the geometry to
  38716. * @returns the new {BABYLON.Geometry}
  38717. */
  38718. Geometry.CreateGeometryForMesh = function (mesh) {
  38719. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38720. geometry.applyToMesh(mesh);
  38721. return geometry;
  38722. };
  38723. Object.defineProperty(Geometry.prototype, "extend", {
  38724. /**
  38725. * Gets the current extend of the geometry
  38726. */
  38727. get: function () {
  38728. return this._extend;
  38729. },
  38730. enumerable: true,
  38731. configurable: true
  38732. });
  38733. /**
  38734. * Gets the hosting scene
  38735. * @returns the hosting {BABYLON.Scene}
  38736. */
  38737. Geometry.prototype.getScene = function () {
  38738. return this._scene;
  38739. };
  38740. /**
  38741. * Gets the hosting engine
  38742. * @returns the hosting {BABYLON.Engine}
  38743. */
  38744. Geometry.prototype.getEngine = function () {
  38745. return this._engine;
  38746. };
  38747. /**
  38748. * Defines if the geometry is ready to use
  38749. * @returns true if the geometry is ready to be used
  38750. */
  38751. Geometry.prototype.isReady = function () {
  38752. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38753. };
  38754. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38755. /**
  38756. * Gets a value indicating that the geometry should not be serialized
  38757. */
  38758. get: function () {
  38759. for (var index = 0; index < this._meshes.length; index++) {
  38760. if (!this._meshes[index].doNotSerialize) {
  38761. return false;
  38762. }
  38763. }
  38764. return true;
  38765. },
  38766. enumerable: true,
  38767. configurable: true
  38768. });
  38769. /** @hidden */
  38770. Geometry.prototype._rebuild = function () {
  38771. if (this._vertexArrayObjects) {
  38772. this._vertexArrayObjects = {};
  38773. }
  38774. // Index buffer
  38775. if (this._meshes.length !== 0 && this._indices) {
  38776. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38777. }
  38778. // Vertex buffers
  38779. for (var key in this._vertexBuffers) {
  38780. var vertexBuffer = this._vertexBuffers[key];
  38781. vertexBuffer._rebuild();
  38782. }
  38783. };
  38784. /**
  38785. * Affects all gemetry data in one call
  38786. * @param vertexData defines the geometry data
  38787. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38788. */
  38789. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38790. vertexData.applyToGeometry(this, updatable);
  38791. this.notifyUpdate();
  38792. };
  38793. /**
  38794. * Set specific vertex data
  38795. * @param kind defines the data kind (Position, normal, etc...)
  38796. * @param data defines the vertex data to use
  38797. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38798. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38799. */
  38800. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38801. if (updatable === void 0) { updatable = false; }
  38802. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38803. this.setVerticesBuffer(buffer);
  38804. };
  38805. /**
  38806. * Removes a specific vertex data
  38807. * @param kind defines the data kind (Position, normal, etc...)
  38808. */
  38809. Geometry.prototype.removeVerticesData = function (kind) {
  38810. if (this._vertexBuffers[kind]) {
  38811. this._vertexBuffers[kind].dispose();
  38812. delete this._vertexBuffers[kind];
  38813. }
  38814. };
  38815. /**
  38816. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38817. * @param buffer defines the vertex buffer to use
  38818. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38819. */
  38820. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38821. if (totalVertices === void 0) { totalVertices = null; }
  38822. var kind = buffer.getKind();
  38823. if (this._vertexBuffers[kind]) {
  38824. this._vertexBuffers[kind].dispose();
  38825. }
  38826. this._vertexBuffers[kind] = buffer;
  38827. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38828. var data = buffer.getData();
  38829. if (totalVertices != null) {
  38830. this._totalVertices = totalVertices;
  38831. }
  38832. else {
  38833. if (data != null) {
  38834. this._totalVertices = data.length / (buffer.byteStride / 4);
  38835. }
  38836. }
  38837. this._updateExtend(data);
  38838. this._resetPointsArrayCache();
  38839. var meshes = this._meshes;
  38840. var numOfMeshes = meshes.length;
  38841. for (var index = 0; index < numOfMeshes; index++) {
  38842. var mesh = meshes[index];
  38843. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38844. mesh._createGlobalSubMesh(false);
  38845. mesh.computeWorldMatrix(true);
  38846. }
  38847. }
  38848. this.notifyUpdate(kind);
  38849. if (this._vertexArrayObjects) {
  38850. this._disposeVertexArrayObjects();
  38851. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38852. }
  38853. };
  38854. /**
  38855. * Update a specific vertex buffer
  38856. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38857. * It will do nothing if the buffer is not updatable
  38858. * @param kind defines the data kind (Position, normal, etc...)
  38859. * @param data defines the data to use
  38860. * @param offset defines the offset in the target buffer where to store the data
  38861. * @param useBytes set to true if the offset is in bytes
  38862. */
  38863. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38864. if (useBytes === void 0) { useBytes = false; }
  38865. var vertexBuffer = this.getVertexBuffer(kind);
  38866. if (!vertexBuffer) {
  38867. return;
  38868. }
  38869. vertexBuffer.updateDirectly(data, offset, useBytes);
  38870. this.notifyUpdate(kind);
  38871. };
  38872. /**
  38873. * Update a specific vertex buffer
  38874. * This function will create a new buffer if the current one is not updatable
  38875. * @param kind defines the data kind (Position, normal, etc...)
  38876. * @param data defines the data to use
  38877. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38878. */
  38879. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38880. if (updateExtends === void 0) { updateExtends = false; }
  38881. var vertexBuffer = this.getVertexBuffer(kind);
  38882. if (!vertexBuffer) {
  38883. return;
  38884. }
  38885. vertexBuffer.update(data);
  38886. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38887. this._updateBoundingInfo(updateExtends, data);
  38888. }
  38889. this.notifyUpdate(kind);
  38890. };
  38891. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38892. if (updateExtends) {
  38893. this._updateExtend(data);
  38894. }
  38895. var meshes = this._meshes;
  38896. var numOfMeshes = meshes.length;
  38897. this._resetPointsArrayCache();
  38898. for (var index = 0; index < numOfMeshes; index++) {
  38899. var mesh = meshes[index];
  38900. if (updateExtends) {
  38901. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38902. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38903. var subMesh = mesh.subMeshes[subIndex];
  38904. subMesh.refreshBoundingInfo();
  38905. }
  38906. }
  38907. }
  38908. };
  38909. /** @hidden */
  38910. Geometry.prototype._bind = function (effect, indexToBind) {
  38911. if (!effect) {
  38912. return;
  38913. }
  38914. if (indexToBind === undefined) {
  38915. indexToBind = this._indexBuffer;
  38916. }
  38917. var vbs = this.getVertexBuffers();
  38918. if (!vbs) {
  38919. return;
  38920. }
  38921. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38922. this._engine.bindBuffers(vbs, indexToBind, effect);
  38923. return;
  38924. }
  38925. // Using VAO
  38926. if (!this._vertexArrayObjects[effect.key]) {
  38927. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38928. }
  38929. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38930. };
  38931. /**
  38932. * Gets total number of vertices
  38933. * @returns the total number of vertices
  38934. */
  38935. Geometry.prototype.getTotalVertices = function () {
  38936. if (!this.isReady()) {
  38937. return 0;
  38938. }
  38939. return this._totalVertices;
  38940. };
  38941. /**
  38942. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38943. * @param kind defines the data kind (Position, normal, etc...)
  38944. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38945. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38946. * @returns a float array containing vertex data
  38947. */
  38948. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38949. var vertexBuffer = this.getVertexBuffer(kind);
  38950. if (!vertexBuffer) {
  38951. return null;
  38952. }
  38953. var data = vertexBuffer.getData();
  38954. if (!data) {
  38955. return null;
  38956. }
  38957. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38958. var count = this._totalVertices * vertexBuffer.getSize();
  38959. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38960. var copy_1 = new Array(count);
  38961. vertexBuffer.forEach(count, function (value, index) {
  38962. copy_1[index] = value;
  38963. });
  38964. return copy_1;
  38965. }
  38966. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38967. if (data instanceof Array) {
  38968. var offset = vertexBuffer.byteOffset / 4;
  38969. return BABYLON.Tools.Slice(data, offset, offset + count);
  38970. }
  38971. else if (data instanceof ArrayBuffer) {
  38972. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38973. }
  38974. else {
  38975. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38976. }
  38977. }
  38978. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38979. return BABYLON.Tools.Slice(data);
  38980. }
  38981. return data;
  38982. };
  38983. /**
  38984. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38985. * @param kind defines the data kind (Position, normal, etc...)
  38986. * @returns true if the vertex buffer with the specified kind is updatable
  38987. */
  38988. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38989. var vb = this._vertexBuffers[kind];
  38990. if (!vb) {
  38991. return false;
  38992. }
  38993. return vb.isUpdatable();
  38994. };
  38995. /**
  38996. * Gets a specific vertex buffer
  38997. * @param kind defines the data kind (Position, normal, etc...)
  38998. * @returns a {BABYLON.VertexBuffer}
  38999. */
  39000. Geometry.prototype.getVertexBuffer = function (kind) {
  39001. if (!this.isReady()) {
  39002. return null;
  39003. }
  39004. return this._vertexBuffers[kind];
  39005. };
  39006. /**
  39007. * Returns all vertex buffers
  39008. * @return an object holding all vertex buffers indexed by kind
  39009. */
  39010. Geometry.prototype.getVertexBuffers = function () {
  39011. if (!this.isReady()) {
  39012. return null;
  39013. }
  39014. return this._vertexBuffers;
  39015. };
  39016. /**
  39017. * Gets a boolean indicating if specific vertex buffer is present
  39018. * @param kind defines the data kind (Position, normal, etc...)
  39019. * @returns true if data is present
  39020. */
  39021. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39022. if (!this._vertexBuffers) {
  39023. if (this._delayInfo) {
  39024. return this._delayInfo.indexOf(kind) !== -1;
  39025. }
  39026. return false;
  39027. }
  39028. return this._vertexBuffers[kind] !== undefined;
  39029. };
  39030. /**
  39031. * Gets a list of all attached data kinds (Position, normal, etc...)
  39032. * @returns a list of string containing all kinds
  39033. */
  39034. Geometry.prototype.getVerticesDataKinds = function () {
  39035. var result = [];
  39036. var kind;
  39037. if (!this._vertexBuffers && this._delayInfo) {
  39038. for (kind in this._delayInfo) {
  39039. result.push(kind);
  39040. }
  39041. }
  39042. else {
  39043. for (kind in this._vertexBuffers) {
  39044. result.push(kind);
  39045. }
  39046. }
  39047. return result;
  39048. };
  39049. /**
  39050. * Update index buffer
  39051. * @param indices defines the indices to store in the index buffer
  39052. * @param offset defines the offset in the target buffer where to store the data
  39053. */
  39054. Geometry.prototype.updateIndices = function (indices, offset) {
  39055. if (!this._indexBuffer) {
  39056. return;
  39057. }
  39058. if (!this._indexBufferIsUpdatable) {
  39059. this.setIndices(indices, null, true);
  39060. }
  39061. else {
  39062. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39063. }
  39064. };
  39065. /**
  39066. * Creates a new index buffer
  39067. * @param indices defines the indices to store in the index buffer
  39068. * @param totalVertices defines the total number of vertices (could be null)
  39069. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39070. */
  39071. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39072. if (totalVertices === void 0) { totalVertices = null; }
  39073. if (updatable === void 0) { updatable = false; }
  39074. if (this._indexBuffer) {
  39075. this._engine._releaseBuffer(this._indexBuffer);
  39076. }
  39077. this._disposeVertexArrayObjects();
  39078. this._indices = indices;
  39079. this._indexBufferIsUpdatable = updatable;
  39080. if (this._meshes.length !== 0 && this._indices) {
  39081. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39082. }
  39083. if (totalVertices != undefined) { // including null and undefined
  39084. this._totalVertices = totalVertices;
  39085. }
  39086. var meshes = this._meshes;
  39087. var numOfMeshes = meshes.length;
  39088. for (var index = 0; index < numOfMeshes; index++) {
  39089. meshes[index]._createGlobalSubMesh(true);
  39090. }
  39091. this.notifyUpdate();
  39092. };
  39093. /**
  39094. * Return the total number of indices
  39095. * @returns the total number of indices
  39096. */
  39097. Geometry.prototype.getTotalIndices = function () {
  39098. if (!this.isReady()) {
  39099. return 0;
  39100. }
  39101. return this._indices.length;
  39102. };
  39103. /**
  39104. * Gets the index buffer array
  39105. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39106. * @returns the index buffer array
  39107. */
  39108. Geometry.prototype.getIndices = function (copyWhenShared) {
  39109. if (!this.isReady()) {
  39110. return null;
  39111. }
  39112. var orig = this._indices;
  39113. if (!copyWhenShared || this._meshes.length === 1) {
  39114. return orig;
  39115. }
  39116. else {
  39117. var len = orig.length;
  39118. var copy = [];
  39119. for (var i = 0; i < len; i++) {
  39120. copy.push(orig[i]);
  39121. }
  39122. return copy;
  39123. }
  39124. };
  39125. /**
  39126. * Gets the index buffer
  39127. * @return the index buffer
  39128. */
  39129. Geometry.prototype.getIndexBuffer = function () {
  39130. if (!this.isReady()) {
  39131. return null;
  39132. }
  39133. return this._indexBuffer;
  39134. };
  39135. /** @hidden */
  39136. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39137. if (effect === void 0) { effect = null; }
  39138. if (!effect || !this._vertexArrayObjects) {
  39139. return;
  39140. }
  39141. if (this._vertexArrayObjects[effect.key]) {
  39142. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39143. delete this._vertexArrayObjects[effect.key];
  39144. }
  39145. };
  39146. /**
  39147. * Release the associated resources for a specific mesh
  39148. * @param mesh defines the source mesh
  39149. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39150. */
  39151. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39152. var meshes = this._meshes;
  39153. var index = meshes.indexOf(mesh);
  39154. if (index === -1) {
  39155. return;
  39156. }
  39157. meshes.splice(index, 1);
  39158. mesh._geometry = null;
  39159. if (meshes.length === 0 && shouldDispose) {
  39160. this.dispose();
  39161. }
  39162. };
  39163. /**
  39164. * Apply current geometry to a given mesh
  39165. * @param mesh defines the mesh to apply geometry to
  39166. */
  39167. Geometry.prototype.applyToMesh = function (mesh) {
  39168. if (mesh._geometry === this) {
  39169. return;
  39170. }
  39171. var previousGeometry = mesh._geometry;
  39172. if (previousGeometry) {
  39173. previousGeometry.releaseForMesh(mesh);
  39174. }
  39175. var meshes = this._meshes;
  39176. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39177. mesh._geometry = this;
  39178. this._scene.pushGeometry(this);
  39179. meshes.push(mesh);
  39180. if (this.isReady()) {
  39181. this._applyToMesh(mesh);
  39182. }
  39183. else {
  39184. mesh._boundingInfo = this._boundingInfo;
  39185. }
  39186. };
  39187. Geometry.prototype._updateExtend = function (data) {
  39188. if (data === void 0) { data = null; }
  39189. if (!data) {
  39190. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39191. }
  39192. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39193. };
  39194. Geometry.prototype._applyToMesh = function (mesh) {
  39195. var numOfMeshes = this._meshes.length;
  39196. // vertexBuffers
  39197. for (var kind in this._vertexBuffers) {
  39198. if (numOfMeshes === 1) {
  39199. this._vertexBuffers[kind].create();
  39200. }
  39201. var buffer = this._vertexBuffers[kind].getBuffer();
  39202. if (buffer)
  39203. buffer.references = numOfMeshes;
  39204. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39205. if (!this._extend) {
  39206. this._updateExtend();
  39207. }
  39208. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39209. mesh._createGlobalSubMesh(false);
  39210. //bounding info was just created again, world matrix should be applied again.
  39211. mesh._updateBoundingInfo();
  39212. }
  39213. }
  39214. // indexBuffer
  39215. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39216. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39217. }
  39218. if (this._indexBuffer) {
  39219. this._indexBuffer.references = numOfMeshes;
  39220. }
  39221. };
  39222. Geometry.prototype.notifyUpdate = function (kind) {
  39223. if (this.onGeometryUpdated) {
  39224. this.onGeometryUpdated(this, kind);
  39225. }
  39226. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39227. var mesh = _a[_i];
  39228. mesh._markSubMeshesAsAttributesDirty();
  39229. }
  39230. };
  39231. /**
  39232. * Load the geometry if it was flagged as delay loaded
  39233. * @param scene defines the hosting scene
  39234. * @param onLoaded defines a callback called when the geometry is loaded
  39235. */
  39236. Geometry.prototype.load = function (scene, onLoaded) {
  39237. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39238. return;
  39239. }
  39240. if (this.isReady()) {
  39241. if (onLoaded) {
  39242. onLoaded();
  39243. }
  39244. return;
  39245. }
  39246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39247. this._queueLoad(scene, onLoaded);
  39248. };
  39249. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39250. var _this = this;
  39251. if (!this.delayLoadingFile) {
  39252. return;
  39253. }
  39254. scene._addPendingData(this);
  39255. scene._loadFile(this.delayLoadingFile, function (data) {
  39256. if (!_this._delayLoadingFunction) {
  39257. return;
  39258. }
  39259. _this._delayLoadingFunction(JSON.parse(data), _this);
  39260. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39261. _this._delayInfo = [];
  39262. scene._removePendingData(_this);
  39263. var meshes = _this._meshes;
  39264. var numOfMeshes = meshes.length;
  39265. for (var index = 0; index < numOfMeshes; index++) {
  39266. _this._applyToMesh(meshes[index]);
  39267. }
  39268. if (onLoaded) {
  39269. onLoaded();
  39270. }
  39271. }, undefined, true);
  39272. };
  39273. /**
  39274. * Invert the geometry to move from a right handed system to a left handed one.
  39275. */
  39276. Geometry.prototype.toLeftHanded = function () {
  39277. // Flip faces
  39278. var tIndices = this.getIndices(false);
  39279. if (tIndices != null && tIndices.length > 0) {
  39280. for (var i = 0; i < tIndices.length; i += 3) {
  39281. var tTemp = tIndices[i + 0];
  39282. tIndices[i + 0] = tIndices[i + 2];
  39283. tIndices[i + 2] = tTemp;
  39284. }
  39285. this.setIndices(tIndices);
  39286. }
  39287. // Negate position.z
  39288. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39289. if (tPositions != null && tPositions.length > 0) {
  39290. for (var i = 0; i < tPositions.length; i += 3) {
  39291. tPositions[i + 2] = -tPositions[i + 2];
  39292. }
  39293. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39294. }
  39295. // Negate normal.z
  39296. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39297. if (tNormals != null && tNormals.length > 0) {
  39298. for (var i = 0; i < tNormals.length; i += 3) {
  39299. tNormals[i + 2] = -tNormals[i + 2];
  39300. }
  39301. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39302. }
  39303. };
  39304. // Cache
  39305. /** @hidden */
  39306. Geometry.prototype._resetPointsArrayCache = function () {
  39307. this._positions = null;
  39308. };
  39309. /** @hidden */
  39310. Geometry.prototype._generatePointsArray = function () {
  39311. if (this._positions)
  39312. return true;
  39313. this._positions = [];
  39314. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39315. if (!data) {
  39316. return false;
  39317. }
  39318. for (var index = 0; index < data.length; index += 3) {
  39319. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39320. }
  39321. return true;
  39322. };
  39323. /**
  39324. * Gets a value indicating if the geometry is disposed
  39325. * @returns true if the geometry was disposed
  39326. */
  39327. Geometry.prototype.isDisposed = function () {
  39328. return this._isDisposed;
  39329. };
  39330. Geometry.prototype._disposeVertexArrayObjects = function () {
  39331. if (this._vertexArrayObjects) {
  39332. for (var kind in this._vertexArrayObjects) {
  39333. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39334. }
  39335. this._vertexArrayObjects = {};
  39336. }
  39337. };
  39338. /**
  39339. * Free all associated resources
  39340. */
  39341. Geometry.prototype.dispose = function () {
  39342. var meshes = this._meshes;
  39343. var numOfMeshes = meshes.length;
  39344. var index;
  39345. for (index = 0; index < numOfMeshes; index++) {
  39346. this.releaseForMesh(meshes[index]);
  39347. }
  39348. this._meshes = [];
  39349. this._disposeVertexArrayObjects();
  39350. for (var kind in this._vertexBuffers) {
  39351. this._vertexBuffers[kind].dispose();
  39352. }
  39353. this._vertexBuffers = {};
  39354. this._totalVertices = 0;
  39355. if (this._indexBuffer) {
  39356. this._engine._releaseBuffer(this._indexBuffer);
  39357. }
  39358. this._indexBuffer = null;
  39359. this._indices = [];
  39360. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39361. this.delayLoadingFile = null;
  39362. this._delayLoadingFunction = null;
  39363. this._delayInfo = [];
  39364. this._boundingInfo = null;
  39365. this._scene.removeGeometry(this);
  39366. this._isDisposed = true;
  39367. };
  39368. /**
  39369. * Clone the current geometry into a new geometry
  39370. * @param id defines the unique ID of the new geometry
  39371. * @returns a new geometry object
  39372. */
  39373. Geometry.prototype.copy = function (id) {
  39374. var vertexData = new BABYLON.VertexData();
  39375. vertexData.indices = [];
  39376. var indices = this.getIndices();
  39377. if (indices) {
  39378. for (var index = 0; index < indices.length; index++) {
  39379. vertexData.indices.push(indices[index]);
  39380. }
  39381. }
  39382. var updatable = false;
  39383. var stopChecking = false;
  39384. var kind;
  39385. for (kind in this._vertexBuffers) {
  39386. // using slice() to make a copy of the array and not just reference it
  39387. var data = this.getVerticesData(kind);
  39388. if (data instanceof Float32Array) {
  39389. vertexData.set(new Float32Array(data), kind);
  39390. }
  39391. else {
  39392. vertexData.set(data.slice(0), kind);
  39393. }
  39394. if (!stopChecking) {
  39395. var vb = this.getVertexBuffer(kind);
  39396. if (vb) {
  39397. updatable = vb.isUpdatable();
  39398. stopChecking = !updatable;
  39399. }
  39400. }
  39401. }
  39402. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39403. geometry.delayLoadState = this.delayLoadState;
  39404. geometry.delayLoadingFile = this.delayLoadingFile;
  39405. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39406. for (kind in this._delayInfo) {
  39407. geometry._delayInfo = geometry._delayInfo || [];
  39408. geometry._delayInfo.push(kind);
  39409. }
  39410. // Bounding info
  39411. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39412. return geometry;
  39413. };
  39414. /**
  39415. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39416. * @return a JSON representation of the current geometry data (without the vertices data)
  39417. */
  39418. Geometry.prototype.serialize = function () {
  39419. var serializationObject = {};
  39420. serializationObject.id = this.id;
  39421. serializationObject.updatable = this._updatable;
  39422. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39423. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39424. }
  39425. return serializationObject;
  39426. };
  39427. Geometry.prototype.toNumberArray = function (origin) {
  39428. if (Array.isArray(origin)) {
  39429. return origin;
  39430. }
  39431. else {
  39432. return Array.prototype.slice.call(origin);
  39433. }
  39434. };
  39435. /**
  39436. * Serialize all vertices data into a JSON oject
  39437. * @returns a JSON representation of the current geometry data
  39438. */
  39439. Geometry.prototype.serializeVerticeData = function () {
  39440. var serializationObject = this.serialize();
  39441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39442. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39443. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39444. serializationObject.positions._updatable = true;
  39445. }
  39446. }
  39447. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39448. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39449. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39450. serializationObject.normals._updatable = true;
  39451. }
  39452. }
  39453. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39454. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39455. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39456. serializationObject.tangets._updatable = true;
  39457. }
  39458. }
  39459. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39460. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39461. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39462. serializationObject.uvs._updatable = true;
  39463. }
  39464. }
  39465. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39466. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39467. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39468. serializationObject.uv2s._updatable = true;
  39469. }
  39470. }
  39471. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39472. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39473. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39474. serializationObject.uv3s._updatable = true;
  39475. }
  39476. }
  39477. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39478. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39479. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39480. serializationObject.uv4s._updatable = true;
  39481. }
  39482. }
  39483. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39484. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39485. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39486. serializationObject.uv5s._updatable = true;
  39487. }
  39488. }
  39489. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39490. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39491. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39492. serializationObject.uv6s._updatable = true;
  39493. }
  39494. }
  39495. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39496. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39497. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39498. serializationObject.colors._updatable = true;
  39499. }
  39500. }
  39501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39502. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39503. serializationObject.matricesIndices._isExpanded = true;
  39504. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39505. serializationObject.matricesIndices._updatable = true;
  39506. }
  39507. }
  39508. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39509. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39510. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39511. serializationObject.matricesWeights._updatable = true;
  39512. }
  39513. }
  39514. serializationObject.indices = this.toNumberArray(this.getIndices());
  39515. return serializationObject;
  39516. };
  39517. // Statics
  39518. /**
  39519. * Extracts a clone of a mesh geometry
  39520. * @param mesh defines the source mesh
  39521. * @param id defines the unique ID of the new geometry object
  39522. * @returns the new geometry object
  39523. */
  39524. Geometry.ExtractFromMesh = function (mesh, id) {
  39525. var geometry = mesh._geometry;
  39526. if (!geometry) {
  39527. return null;
  39528. }
  39529. return geometry.copy(id);
  39530. };
  39531. /**
  39532. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39533. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39534. * Be aware Math.random() could cause collisions, but:
  39535. * "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"
  39536. * @returns a string containing a new GUID
  39537. */
  39538. Geometry.RandomId = function () {
  39539. return BABYLON.Tools.RandomId();
  39540. };
  39541. /** @hidden */
  39542. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39543. var scene = mesh.getScene();
  39544. // Geometry
  39545. var geometryId = parsedGeometry.geometryId;
  39546. if (geometryId) {
  39547. var geometry = scene.getGeometryByID(geometryId);
  39548. if (geometry) {
  39549. geometry.applyToMesh(mesh);
  39550. }
  39551. }
  39552. else if (parsedGeometry instanceof ArrayBuffer) {
  39553. var binaryInfo = mesh._binaryInfo;
  39554. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39555. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39556. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39557. }
  39558. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39559. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39560. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39561. }
  39562. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39563. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39564. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39565. }
  39566. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39567. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39568. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39569. }
  39570. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39571. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39572. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39573. }
  39574. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39575. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39576. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39577. }
  39578. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39579. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39580. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39581. }
  39582. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39583. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39584. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39585. }
  39586. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39587. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39588. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39589. }
  39590. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39591. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39592. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39593. }
  39594. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39595. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39597. }
  39598. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39599. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39601. }
  39602. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39603. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39604. mesh.setIndices(indicesData, null);
  39605. }
  39606. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39607. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39608. mesh.subMeshes = [];
  39609. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39610. var materialIndex = subMeshesData[(i * 5) + 0];
  39611. var verticesStart = subMeshesData[(i * 5) + 1];
  39612. var verticesCount = subMeshesData[(i * 5) + 2];
  39613. var indexStart = subMeshesData[(i * 5) + 3];
  39614. var indexCount = subMeshesData[(i * 5) + 4];
  39615. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39616. }
  39617. }
  39618. }
  39619. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39620. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39621. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39622. if (parsedGeometry.tangents) {
  39623. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39624. }
  39625. if (parsedGeometry.uvs) {
  39626. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39627. }
  39628. if (parsedGeometry.uvs2) {
  39629. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39630. }
  39631. if (parsedGeometry.uvs3) {
  39632. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39633. }
  39634. if (parsedGeometry.uvs4) {
  39635. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39636. }
  39637. if (parsedGeometry.uvs5) {
  39638. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39639. }
  39640. if (parsedGeometry.uvs6) {
  39641. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39642. }
  39643. if (parsedGeometry.colors) {
  39644. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39645. }
  39646. if (parsedGeometry.matricesIndices) {
  39647. if (!parsedGeometry.matricesIndices._isExpanded) {
  39648. var floatIndices = [];
  39649. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39650. var matricesIndex = parsedGeometry.matricesIndices[i];
  39651. floatIndices.push(matricesIndex & 0x000000FF);
  39652. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39653. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39654. floatIndices.push(matricesIndex >> 24);
  39655. }
  39656. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39657. }
  39658. else {
  39659. delete parsedGeometry.matricesIndices._isExpanded;
  39660. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39661. }
  39662. }
  39663. if (parsedGeometry.matricesIndicesExtra) {
  39664. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39665. var floatIndices = [];
  39666. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39667. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39668. floatIndices.push(matricesIndex & 0x000000FF);
  39669. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39670. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39671. floatIndices.push(matricesIndex >> 24);
  39672. }
  39673. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39674. }
  39675. else {
  39676. delete parsedGeometry.matricesIndices._isExpanded;
  39677. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39678. }
  39679. }
  39680. if (parsedGeometry.matricesWeights) {
  39681. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39683. }
  39684. if (parsedGeometry.matricesWeightsExtra) {
  39685. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39686. }
  39687. mesh.setIndices(parsedGeometry.indices, null);
  39688. }
  39689. // SubMeshes
  39690. if (parsedGeometry.subMeshes) {
  39691. mesh.subMeshes = [];
  39692. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39693. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39694. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39695. }
  39696. }
  39697. // Flat shading
  39698. if (mesh._shouldGenerateFlatShading) {
  39699. mesh.convertToFlatShadedMesh();
  39700. delete mesh._shouldGenerateFlatShading;
  39701. }
  39702. // Update
  39703. mesh.computeWorldMatrix(true);
  39704. // Octree
  39705. var sceneOctree = scene.selectionOctree;
  39706. if (sceneOctree !== undefined && sceneOctree !== null) {
  39707. sceneOctree.addMesh(mesh);
  39708. }
  39709. };
  39710. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39711. var epsilon = 1e-3;
  39712. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39713. return;
  39714. }
  39715. var noInfluenceBoneIndex = 0.0;
  39716. if (parsedGeometry.skeletonId > -1) {
  39717. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39718. if (!skeleton) {
  39719. return;
  39720. }
  39721. noInfluenceBoneIndex = skeleton.bones.length;
  39722. }
  39723. else {
  39724. return;
  39725. }
  39726. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39727. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39728. var matricesWeights = parsedGeometry.matricesWeights;
  39729. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39730. var influencers = parsedGeometry.numBoneInfluencer;
  39731. var size = matricesWeights.length;
  39732. for (var i = 0; i < size; i += 4) {
  39733. var weight = 0.0;
  39734. var firstZeroWeight = -1;
  39735. for (var j = 0; j < 4; j++) {
  39736. var w = matricesWeights[i + j];
  39737. weight += w;
  39738. if (w < epsilon && firstZeroWeight < 0) {
  39739. firstZeroWeight = j;
  39740. }
  39741. }
  39742. if (matricesWeightsExtra) {
  39743. for (var j = 0; j < 4; j++) {
  39744. var w = matricesWeightsExtra[i + j];
  39745. weight += w;
  39746. if (w < epsilon && firstZeroWeight < 0) {
  39747. firstZeroWeight = j + 4;
  39748. }
  39749. }
  39750. }
  39751. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39752. firstZeroWeight = influencers - 1;
  39753. }
  39754. if (weight > epsilon) {
  39755. var mweight = 1.0 / weight;
  39756. for (var j = 0; j < 4; j++) {
  39757. matricesWeights[i + j] *= mweight;
  39758. }
  39759. if (matricesWeightsExtra) {
  39760. for (var j = 0; j < 4; j++) {
  39761. matricesWeightsExtra[i + j] *= mweight;
  39762. }
  39763. }
  39764. }
  39765. else {
  39766. if (firstZeroWeight >= 4) {
  39767. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39768. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39769. }
  39770. else {
  39771. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39772. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39773. }
  39774. }
  39775. }
  39776. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39777. if (parsedGeometry.matricesWeightsExtra) {
  39778. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39779. }
  39780. };
  39781. /**
  39782. * Create a new geometry from persisted data (Using .babylon file format)
  39783. * @param parsedVertexData defines the persisted data
  39784. * @param scene defines the hosting scene
  39785. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39786. * @returns the new geometry object
  39787. */
  39788. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39789. if (scene.getGeometryByID(parsedVertexData.id)) {
  39790. return null; // null since geometry could be something else than a box...
  39791. }
  39792. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39793. if (BABYLON.Tags) {
  39794. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39795. }
  39796. if (parsedVertexData.delayLoadingFile) {
  39797. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39798. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39799. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39800. geometry._delayInfo = [];
  39801. if (parsedVertexData.hasUVs) {
  39802. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39803. }
  39804. if (parsedVertexData.hasUVs2) {
  39805. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39806. }
  39807. if (parsedVertexData.hasUVs3) {
  39808. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39809. }
  39810. if (parsedVertexData.hasUVs4) {
  39811. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39812. }
  39813. if (parsedVertexData.hasUVs5) {
  39814. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39815. }
  39816. if (parsedVertexData.hasUVs6) {
  39817. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39818. }
  39819. if (parsedVertexData.hasColors) {
  39820. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39821. }
  39822. if (parsedVertexData.hasMatricesIndices) {
  39823. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39824. }
  39825. if (parsedVertexData.hasMatricesWeights) {
  39826. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39827. }
  39828. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39829. }
  39830. else {
  39831. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39832. }
  39833. scene.pushGeometry(geometry, true);
  39834. return geometry;
  39835. };
  39836. return Geometry;
  39837. }());
  39838. BABYLON.Geometry = Geometry;
  39839. // Primitives
  39840. /// Abstract class
  39841. /**
  39842. * Abstract class used to provide common services for all typed geometries
  39843. * @hidden
  39844. */
  39845. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39846. __extends(_PrimitiveGeometry, _super);
  39847. /**
  39848. * Creates a new typed geometry
  39849. * @param id defines the unique ID of the geometry
  39850. * @param scene defines the hosting scene
  39851. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39852. * @param mesh defines the hosting mesh (can be null)
  39853. */
  39854. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39855. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39856. if (mesh === void 0) { mesh = null; }
  39857. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39858. _this._canBeRegenerated = _canBeRegenerated;
  39859. _this._beingRegenerated = true;
  39860. _this.regenerate();
  39861. _this._beingRegenerated = false;
  39862. return _this;
  39863. }
  39864. /**
  39865. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39866. * @returns true if the geometry can be regenerated
  39867. */
  39868. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39869. return this._canBeRegenerated;
  39870. };
  39871. /**
  39872. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39873. */
  39874. _PrimitiveGeometry.prototype.regenerate = function () {
  39875. if (!this._canBeRegenerated) {
  39876. return;
  39877. }
  39878. this._beingRegenerated = true;
  39879. this.setAllVerticesData(this._regenerateVertexData(), false);
  39880. this._beingRegenerated = false;
  39881. };
  39882. /**
  39883. * Clone the geometry
  39884. * @param id defines the unique ID of the new geometry
  39885. * @returns the new geometry
  39886. */
  39887. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39888. return _super.prototype.copy.call(this, id);
  39889. };
  39890. // overrides
  39891. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39892. if (!this._beingRegenerated) {
  39893. return;
  39894. }
  39895. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39896. };
  39897. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39898. if (!this._beingRegenerated) {
  39899. return;
  39900. }
  39901. _super.prototype.setVerticesData.call(this, kind, data, false);
  39902. };
  39903. // to override
  39904. /** @hidden */
  39905. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39906. throw new Error("Abstract method");
  39907. };
  39908. _PrimitiveGeometry.prototype.copy = function (id) {
  39909. throw new Error("Must be overriden in sub-classes.");
  39910. };
  39911. _PrimitiveGeometry.prototype.serialize = function () {
  39912. var serializationObject = _super.prototype.serialize.call(this);
  39913. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39914. return serializationObject;
  39915. };
  39916. return _PrimitiveGeometry;
  39917. }(Geometry));
  39918. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39919. /**
  39920. * Creates a ribbon geometry
  39921. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39922. */
  39923. var RibbonGeometry = /** @class */ (function (_super) {
  39924. __extends(RibbonGeometry, _super);
  39925. /**
  39926. * Creates a ribbon geometry
  39927. * @param id defines the unique ID of the geometry
  39928. * @param scene defines the hosting scene
  39929. * @param pathArray defines the array of paths to use
  39930. * @param closeArray defines if the last path and the first path must be joined
  39931. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39932. * @param offset defines the offset between points
  39933. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39934. * @param mesh defines the hosting mesh (can be null)
  39935. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39936. */
  39937. function RibbonGeometry(id, scene,
  39938. /**
  39939. * Defines the array of paths to use
  39940. */
  39941. pathArray,
  39942. /**
  39943. * Defines if the last and first points of each path in your pathArray must be joined
  39944. */
  39945. closeArray,
  39946. /**
  39947. * Defines if the last and first points of each path in your pathArray must be joined
  39948. */
  39949. closePath,
  39950. /**
  39951. * Defines the offset between points
  39952. */
  39953. offset, canBeRegenerated, mesh,
  39954. /**
  39955. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39956. */
  39957. side) {
  39958. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39959. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39960. _this.pathArray = pathArray;
  39961. _this.closeArray = closeArray;
  39962. _this.closePath = closePath;
  39963. _this.offset = offset;
  39964. _this.side = side;
  39965. return _this;
  39966. }
  39967. /** @hidden */
  39968. RibbonGeometry.prototype._regenerateVertexData = function () {
  39969. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39970. };
  39971. RibbonGeometry.prototype.copy = function (id) {
  39972. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39973. };
  39974. return RibbonGeometry;
  39975. }(_PrimitiveGeometry));
  39976. BABYLON.RibbonGeometry = RibbonGeometry;
  39977. /**
  39978. * Creates a box geometry
  39979. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39980. */
  39981. var BoxGeometry = /** @class */ (function (_super) {
  39982. __extends(BoxGeometry, _super);
  39983. /**
  39984. * Creates a box geometry
  39985. * @param id defines the unique ID of the geometry
  39986. * @param scene defines the hosting scene
  39987. * @param size defines the zise of the box (width, height and depth are the same)
  39988. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39989. * @param mesh defines the hosting mesh (can be null)
  39990. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39991. */
  39992. function BoxGeometry(id, scene,
  39993. /**
  39994. * Defines the zise of the box (width, height and depth are the same)
  39995. */
  39996. size, canBeRegenerated, mesh,
  39997. /**
  39998. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39999. */
  40000. side) {
  40001. if (mesh === void 0) { mesh = null; }
  40002. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40003. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40004. _this.size = size;
  40005. _this.side = side;
  40006. return _this;
  40007. }
  40008. BoxGeometry.prototype._regenerateVertexData = function () {
  40009. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40010. };
  40011. BoxGeometry.prototype.copy = function (id) {
  40012. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40013. };
  40014. BoxGeometry.prototype.serialize = function () {
  40015. var serializationObject = _super.prototype.serialize.call(this);
  40016. serializationObject.size = this.size;
  40017. return serializationObject;
  40018. };
  40019. BoxGeometry.Parse = function (parsedBox, scene) {
  40020. if (scene.getGeometryByID(parsedBox.id)) {
  40021. return null; // null since geometry could be something else than a box...
  40022. }
  40023. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40024. if (BABYLON.Tags) {
  40025. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40026. }
  40027. scene.pushGeometry(box, true);
  40028. return box;
  40029. };
  40030. return BoxGeometry;
  40031. }(_PrimitiveGeometry));
  40032. BABYLON.BoxGeometry = BoxGeometry;
  40033. /**
  40034. * Creates a sphere geometry
  40035. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40036. */
  40037. var SphereGeometry = /** @class */ (function (_super) {
  40038. __extends(SphereGeometry, _super);
  40039. /**
  40040. * Create a new sphere geometry
  40041. * @param id defines the unique ID of the geometry
  40042. * @param scene defines the hosting scene
  40043. * @param segments defines the number of segments to use to create the sphere
  40044. * @param diameter defines the diameter of the sphere
  40045. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40046. * @param mesh defines the hosting mesh (can be null)
  40047. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40048. */
  40049. function SphereGeometry(id, scene,
  40050. /**
  40051. * Defines the number of segments to use to create the sphere
  40052. */
  40053. segments,
  40054. /**
  40055. * Defines the diameter of the sphere
  40056. */
  40057. diameter, canBeRegenerated, mesh,
  40058. /**
  40059. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40060. */
  40061. side) {
  40062. if (mesh === void 0) { mesh = null; }
  40063. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40064. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40065. _this.segments = segments;
  40066. _this.diameter = diameter;
  40067. _this.side = side;
  40068. return _this;
  40069. }
  40070. SphereGeometry.prototype._regenerateVertexData = function () {
  40071. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40072. };
  40073. SphereGeometry.prototype.copy = function (id) {
  40074. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40075. };
  40076. SphereGeometry.prototype.serialize = function () {
  40077. var serializationObject = _super.prototype.serialize.call(this);
  40078. serializationObject.segments = this.segments;
  40079. serializationObject.diameter = this.diameter;
  40080. return serializationObject;
  40081. };
  40082. SphereGeometry.Parse = function (parsedSphere, scene) {
  40083. if (scene.getGeometryByID(parsedSphere.id)) {
  40084. return null; // null since geometry could be something else than a sphere...
  40085. }
  40086. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40087. if (BABYLON.Tags) {
  40088. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40089. }
  40090. scene.pushGeometry(sphere, true);
  40091. return sphere;
  40092. };
  40093. return SphereGeometry;
  40094. }(_PrimitiveGeometry));
  40095. BABYLON.SphereGeometry = SphereGeometry;
  40096. /**
  40097. * Creates a disc geometry
  40098. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40099. */
  40100. var DiscGeometry = /** @class */ (function (_super) {
  40101. __extends(DiscGeometry, _super);
  40102. /**
  40103. * Creates a new disc geometry
  40104. * @param id defines the unique ID of the geometry
  40105. * @param scene defines the hosting scene
  40106. * @param radius defines the radius of the disc
  40107. * @param tessellation defines the tesselation factor to apply to the disc
  40108. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40109. * @param mesh defines the hosting mesh (can be null)
  40110. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40111. */
  40112. function DiscGeometry(id, scene,
  40113. /**
  40114. * Defines the radius of the disc
  40115. */
  40116. radius,
  40117. /**
  40118. * Defines the tesselation factor to apply to the disc
  40119. */
  40120. tessellation, canBeRegenerated, mesh,
  40121. /**
  40122. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40123. */
  40124. side) {
  40125. if (mesh === void 0) { mesh = null; }
  40126. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40127. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40128. _this.radius = radius;
  40129. _this.tessellation = tessellation;
  40130. _this.side = side;
  40131. return _this;
  40132. }
  40133. DiscGeometry.prototype._regenerateVertexData = function () {
  40134. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40135. };
  40136. DiscGeometry.prototype.copy = function (id) {
  40137. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40138. };
  40139. return DiscGeometry;
  40140. }(_PrimitiveGeometry));
  40141. BABYLON.DiscGeometry = DiscGeometry;
  40142. /**
  40143. * Creates a new cylinder geometry
  40144. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40145. */
  40146. var CylinderGeometry = /** @class */ (function (_super) {
  40147. __extends(CylinderGeometry, _super);
  40148. /**
  40149. * Creates a new cylinder geometry
  40150. * @param id defines the unique ID of the geometry
  40151. * @param scene defines the hosting scene
  40152. * @param height defines the height of the cylinder
  40153. * @param diameterTop defines the diameter of the cylinder's top cap
  40154. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40155. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40156. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40157. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40158. * @param mesh defines the hosting mesh (can be null)
  40159. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40160. */
  40161. function CylinderGeometry(id, scene,
  40162. /**
  40163. * Defines the height of the cylinder
  40164. */
  40165. height,
  40166. /**
  40167. * Defines the diameter of the cylinder's top cap
  40168. */
  40169. diameterTop,
  40170. /**
  40171. * Defines the diameter of the cylinder's bottom cap
  40172. */
  40173. diameterBottom,
  40174. /**
  40175. * Defines the tessellation factor to apply to the cylinder
  40176. */
  40177. tessellation,
  40178. /**
  40179. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40180. */
  40181. subdivisions, canBeRegenerated, mesh,
  40182. /**
  40183. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40184. */
  40185. side) {
  40186. if (subdivisions === void 0) { subdivisions = 1; }
  40187. if (mesh === void 0) { mesh = null; }
  40188. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40189. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40190. _this.height = height;
  40191. _this.diameterTop = diameterTop;
  40192. _this.diameterBottom = diameterBottom;
  40193. _this.tessellation = tessellation;
  40194. _this.subdivisions = subdivisions;
  40195. _this.side = side;
  40196. return _this;
  40197. }
  40198. CylinderGeometry.prototype._regenerateVertexData = function () {
  40199. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40200. };
  40201. CylinderGeometry.prototype.copy = function (id) {
  40202. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40203. };
  40204. CylinderGeometry.prototype.serialize = function () {
  40205. var serializationObject = _super.prototype.serialize.call(this);
  40206. serializationObject.height = this.height;
  40207. serializationObject.diameterTop = this.diameterTop;
  40208. serializationObject.diameterBottom = this.diameterBottom;
  40209. serializationObject.tessellation = this.tessellation;
  40210. return serializationObject;
  40211. };
  40212. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40213. if (scene.getGeometryByID(parsedCylinder.id)) {
  40214. return null; // null since geometry could be something else than a cylinder...
  40215. }
  40216. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40217. if (BABYLON.Tags) {
  40218. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40219. }
  40220. scene.pushGeometry(cylinder, true);
  40221. return cylinder;
  40222. };
  40223. return CylinderGeometry;
  40224. }(_PrimitiveGeometry));
  40225. BABYLON.CylinderGeometry = CylinderGeometry;
  40226. /**
  40227. * Creates a new torus geometry
  40228. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40229. */
  40230. var TorusGeometry = /** @class */ (function (_super) {
  40231. __extends(TorusGeometry, _super);
  40232. /**
  40233. * Creates a new torus geometry
  40234. * @param id defines the unique ID of the geometry
  40235. * @param scene defines the hosting scene
  40236. * @param diameter defines the diameter of the torus
  40237. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40238. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40239. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40240. * @param mesh defines the hosting mesh (can be null)
  40241. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40242. */
  40243. function TorusGeometry(id, scene,
  40244. /**
  40245. * Defines the diameter of the torus
  40246. */
  40247. diameter,
  40248. /**
  40249. * Defines the thickness of the torus (ie. internal diameter)
  40250. */
  40251. thickness,
  40252. /**
  40253. * Defines the tesselation factor to apply to the torus
  40254. */
  40255. tessellation, canBeRegenerated, mesh,
  40256. /**
  40257. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40258. */
  40259. side) {
  40260. if (mesh === void 0) { mesh = null; }
  40261. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40262. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40263. _this.diameter = diameter;
  40264. _this.thickness = thickness;
  40265. _this.tessellation = tessellation;
  40266. _this.side = side;
  40267. return _this;
  40268. }
  40269. TorusGeometry.prototype._regenerateVertexData = function () {
  40270. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40271. };
  40272. TorusGeometry.prototype.copy = function (id) {
  40273. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40274. };
  40275. TorusGeometry.prototype.serialize = function () {
  40276. var serializationObject = _super.prototype.serialize.call(this);
  40277. serializationObject.diameter = this.diameter;
  40278. serializationObject.thickness = this.thickness;
  40279. serializationObject.tessellation = this.tessellation;
  40280. return serializationObject;
  40281. };
  40282. TorusGeometry.Parse = function (parsedTorus, scene) {
  40283. if (scene.getGeometryByID(parsedTorus.id)) {
  40284. return null; // null since geometry could be something else than a torus...
  40285. }
  40286. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40287. if (BABYLON.Tags) {
  40288. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40289. }
  40290. scene.pushGeometry(torus, true);
  40291. return torus;
  40292. };
  40293. return TorusGeometry;
  40294. }(_PrimitiveGeometry));
  40295. BABYLON.TorusGeometry = TorusGeometry;
  40296. /**
  40297. * Creates a new ground geometry
  40298. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40299. */
  40300. var GroundGeometry = /** @class */ (function (_super) {
  40301. __extends(GroundGeometry, _super);
  40302. /**
  40303. * Creates a new ground geometry
  40304. * @param id defines the unique ID of the geometry
  40305. * @param scene defines the hosting scene
  40306. * @param width defines the width of the ground
  40307. * @param height defines the height of the ground
  40308. * @param subdivisions defines the subdivisions to apply to the ground
  40309. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40310. * @param mesh defines the hosting mesh (can be null)
  40311. */
  40312. function GroundGeometry(id, scene,
  40313. /**
  40314. * Defines the width of the ground
  40315. */
  40316. width,
  40317. /**
  40318. * Defines the height of the ground
  40319. */
  40320. height,
  40321. /**
  40322. * Defines the subdivisions to apply to the ground
  40323. */
  40324. subdivisions, canBeRegenerated, mesh) {
  40325. if (mesh === void 0) { mesh = null; }
  40326. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40327. _this.width = width;
  40328. _this.height = height;
  40329. _this.subdivisions = subdivisions;
  40330. return _this;
  40331. }
  40332. GroundGeometry.prototype._regenerateVertexData = function () {
  40333. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40334. };
  40335. GroundGeometry.prototype.copy = function (id) {
  40336. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40337. };
  40338. GroundGeometry.prototype.serialize = function () {
  40339. var serializationObject = _super.prototype.serialize.call(this);
  40340. serializationObject.width = this.width;
  40341. serializationObject.height = this.height;
  40342. serializationObject.subdivisions = this.subdivisions;
  40343. return serializationObject;
  40344. };
  40345. GroundGeometry.Parse = function (parsedGround, scene) {
  40346. if (scene.getGeometryByID(parsedGround.id)) {
  40347. return null; // null since geometry could be something else than a ground...
  40348. }
  40349. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40350. if (BABYLON.Tags) {
  40351. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40352. }
  40353. scene.pushGeometry(ground, true);
  40354. return ground;
  40355. };
  40356. return GroundGeometry;
  40357. }(_PrimitiveGeometry));
  40358. BABYLON.GroundGeometry = GroundGeometry;
  40359. /**
  40360. * Creates a tiled ground geometry
  40361. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40362. */
  40363. var TiledGroundGeometry = /** @class */ (function (_super) {
  40364. __extends(TiledGroundGeometry, _super);
  40365. /**
  40366. * Creates a tiled ground geometry
  40367. * @param id defines the unique ID of the geometry
  40368. * @param scene defines the hosting scene
  40369. * @param xmin defines the minimum value on X axis
  40370. * @param zmin defines the minimum value on Z axis
  40371. * @param xmax defines the maximum value on X axis
  40372. * @param zmax defines the maximum value on Z axis
  40373. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40374. * @param precision defines the precision to use when computing the tiles
  40375. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40376. * @param mesh defines the hosting mesh (can be null)
  40377. */
  40378. function TiledGroundGeometry(id, scene,
  40379. /**
  40380. * Defines the minimum value on X axis
  40381. */
  40382. xmin,
  40383. /**
  40384. * Defines the minimum value on Z axis
  40385. */
  40386. zmin,
  40387. /**
  40388. * Defines the maximum value on X axis
  40389. */
  40390. xmax,
  40391. /**
  40392. * Defines the maximum value on Z axis
  40393. */
  40394. zmax,
  40395. /**
  40396. * Defines the subdivisions to apply to the ground
  40397. */
  40398. subdivisions,
  40399. /**
  40400. * Defines the precision to use when computing the tiles
  40401. */
  40402. precision, canBeRegenerated, mesh) {
  40403. if (mesh === void 0) { mesh = null; }
  40404. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40405. _this.xmin = xmin;
  40406. _this.zmin = zmin;
  40407. _this.xmax = xmax;
  40408. _this.zmax = zmax;
  40409. _this.subdivisions = subdivisions;
  40410. _this.precision = precision;
  40411. return _this;
  40412. }
  40413. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40414. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40415. };
  40416. TiledGroundGeometry.prototype.copy = function (id) {
  40417. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40418. };
  40419. return TiledGroundGeometry;
  40420. }(_PrimitiveGeometry));
  40421. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40422. /**
  40423. * Creates a plane geometry
  40424. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40425. */
  40426. var PlaneGeometry = /** @class */ (function (_super) {
  40427. __extends(PlaneGeometry, _super);
  40428. /**
  40429. * Creates a plane geometry
  40430. * @param id defines the unique ID of the geometry
  40431. * @param scene defines the hosting scene
  40432. * @param size defines the size of the plane (width === height)
  40433. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40434. * @param mesh defines the hosting mesh (can be null)
  40435. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40436. */
  40437. function PlaneGeometry(id, scene,
  40438. /**
  40439. * Defines the size of the plane (width === height)
  40440. */
  40441. size, canBeRegenerated, mesh,
  40442. /**
  40443. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40444. */
  40445. side) {
  40446. if (mesh === void 0) { mesh = null; }
  40447. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40449. _this.size = size;
  40450. _this.side = side;
  40451. return _this;
  40452. }
  40453. PlaneGeometry.prototype._regenerateVertexData = function () {
  40454. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40455. };
  40456. PlaneGeometry.prototype.copy = function (id) {
  40457. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40458. };
  40459. PlaneGeometry.prototype.serialize = function () {
  40460. var serializationObject = _super.prototype.serialize.call(this);
  40461. serializationObject.size = this.size;
  40462. return serializationObject;
  40463. };
  40464. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40465. if (scene.getGeometryByID(parsedPlane.id)) {
  40466. return null; // null since geometry could be something else than a ground...
  40467. }
  40468. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40469. if (BABYLON.Tags) {
  40470. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40471. }
  40472. scene.pushGeometry(plane, true);
  40473. return plane;
  40474. };
  40475. return PlaneGeometry;
  40476. }(_PrimitiveGeometry));
  40477. BABYLON.PlaneGeometry = PlaneGeometry;
  40478. /**
  40479. * Creates a torus knot geometry
  40480. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40481. */
  40482. var TorusKnotGeometry = /** @class */ (function (_super) {
  40483. __extends(TorusKnotGeometry, _super);
  40484. /**
  40485. * Creates a torus knot geometry
  40486. * @param id defines the unique ID of the geometry
  40487. * @param scene defines the hosting scene
  40488. * @param radius defines the radius of the torus knot
  40489. * @param tube defines the thickness of the torus knot tube
  40490. * @param radialSegments defines the number of radial segments
  40491. * @param tubularSegments defines the number of tubular segments
  40492. * @param p defines the first number of windings
  40493. * @param q defines the second number of windings
  40494. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40495. * @param mesh defines the hosting mesh (can be null)
  40496. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40497. */
  40498. function TorusKnotGeometry(id, scene,
  40499. /**
  40500. * Defines the radius of the torus knot
  40501. */
  40502. radius,
  40503. /**
  40504. * Defines the thickness of the torus knot tube
  40505. */
  40506. tube,
  40507. /**
  40508. * Defines the number of radial segments
  40509. */
  40510. radialSegments,
  40511. /**
  40512. * Defines the number of tubular segments
  40513. */
  40514. tubularSegments,
  40515. /**
  40516. * Defines the first number of windings
  40517. */
  40518. p,
  40519. /**
  40520. * Defines the second number of windings
  40521. */
  40522. q, canBeRegenerated, mesh,
  40523. /**
  40524. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40525. */
  40526. side) {
  40527. if (mesh === void 0) { mesh = null; }
  40528. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40529. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40530. _this.radius = radius;
  40531. _this.tube = tube;
  40532. _this.radialSegments = radialSegments;
  40533. _this.tubularSegments = tubularSegments;
  40534. _this.p = p;
  40535. _this.q = q;
  40536. _this.side = side;
  40537. return _this;
  40538. }
  40539. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40540. 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 });
  40541. };
  40542. TorusKnotGeometry.prototype.copy = function (id) {
  40543. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40544. };
  40545. TorusKnotGeometry.prototype.serialize = function () {
  40546. var serializationObject = _super.prototype.serialize.call(this);
  40547. serializationObject.radius = this.radius;
  40548. serializationObject.tube = this.tube;
  40549. serializationObject.radialSegments = this.radialSegments;
  40550. serializationObject.tubularSegments = this.tubularSegments;
  40551. serializationObject.p = this.p;
  40552. serializationObject.q = this.q;
  40553. return serializationObject;
  40554. };
  40555. ;
  40556. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40557. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40558. return null; // null since geometry could be something else than a ground...
  40559. }
  40560. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40561. if (BABYLON.Tags) {
  40562. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40563. }
  40564. scene.pushGeometry(torusKnot, true);
  40565. return torusKnot;
  40566. };
  40567. return TorusKnotGeometry;
  40568. }(_PrimitiveGeometry));
  40569. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40570. //}
  40571. })(BABYLON || (BABYLON = {}));
  40572. //# sourceMappingURL=babylon.geometry.js.map
  40573. var BABYLON;
  40574. (function (BABYLON) {
  40575. /**
  40576. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40577. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40578. */
  40579. var PostProcessManager = /** @class */ (function () {
  40580. /**
  40581. * Creates a new instance PostProcess
  40582. * @param scene The scene that the post process is associated with.
  40583. */
  40584. function PostProcessManager(scene) {
  40585. this._vertexBuffers = {};
  40586. this._scene = scene;
  40587. }
  40588. PostProcessManager.prototype._prepareBuffers = function () {
  40589. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40590. return;
  40591. }
  40592. // VBO
  40593. var vertices = [];
  40594. vertices.push(1, 1);
  40595. vertices.push(-1, 1);
  40596. vertices.push(-1, -1);
  40597. vertices.push(1, -1);
  40598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40599. this._buildIndexBuffer();
  40600. };
  40601. PostProcessManager.prototype._buildIndexBuffer = function () {
  40602. // Indices
  40603. var indices = [];
  40604. indices.push(0);
  40605. indices.push(1);
  40606. indices.push(2);
  40607. indices.push(0);
  40608. indices.push(2);
  40609. indices.push(3);
  40610. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40611. };
  40612. /**
  40613. * Rebuilds the vertex buffers of the manager.
  40614. */
  40615. PostProcessManager.prototype._rebuild = function () {
  40616. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40617. if (!vb) {
  40618. return;
  40619. }
  40620. vb._rebuild();
  40621. this._buildIndexBuffer();
  40622. };
  40623. // Methods
  40624. /**
  40625. * Prepares a frame to be run through a post process.
  40626. * @param sourceTexture The input texture to the post procesess. (default: null)
  40627. * @param postProcesses An array of post processes to be run. (default: null)
  40628. * @returns True if the post processes were able to be run.
  40629. */
  40630. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40631. if (sourceTexture === void 0) { sourceTexture = null; }
  40632. if (postProcesses === void 0) { postProcesses = null; }
  40633. var camera = this._scene.activeCamera;
  40634. if (!camera) {
  40635. return false;
  40636. }
  40637. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40638. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40639. return false;
  40640. }
  40641. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40642. return true;
  40643. };
  40644. /**
  40645. * Manually render a set of post processes to a texture.
  40646. * @param postProcesses An array of post processes to be run.
  40647. * @param targetTexture The target texture to render to.
  40648. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40649. */
  40650. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40651. if (targetTexture === void 0) { targetTexture = null; }
  40652. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40653. var engine = this._scene.getEngine();
  40654. for (var index = 0; index < postProcesses.length; index++) {
  40655. if (index < postProcesses.length - 1) {
  40656. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40657. }
  40658. else {
  40659. if (targetTexture) {
  40660. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40661. }
  40662. else {
  40663. engine.restoreDefaultFramebuffer();
  40664. }
  40665. }
  40666. var pp = postProcesses[index];
  40667. var effect = pp.apply();
  40668. if (effect) {
  40669. pp.onBeforeRenderObservable.notifyObservers(effect);
  40670. // VBOs
  40671. this._prepareBuffers();
  40672. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40673. // Draw order
  40674. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40675. pp.onAfterRenderObservable.notifyObservers(effect);
  40676. }
  40677. }
  40678. // Restore depth buffer
  40679. engine.setDepthBuffer(true);
  40680. engine.setDepthWrite(true);
  40681. };
  40682. /**
  40683. * Finalize the result of the output of the postprocesses.
  40684. * @param doNotPresent If true the result will not be displayed to the screen.
  40685. * @param targetTexture The target texture to render to.
  40686. * @param faceIndex The index of the face to bind the target texture to.
  40687. * @param postProcesses The array of post processes to render.
  40688. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40689. */
  40690. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40691. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40692. var camera = this._scene.activeCamera;
  40693. if (!camera) {
  40694. return;
  40695. }
  40696. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40697. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40698. return;
  40699. }
  40700. var engine = this._scene.getEngine();
  40701. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40702. var pp = postProcesses[index];
  40703. if (index < len - 1) {
  40704. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40705. }
  40706. else {
  40707. if (targetTexture) {
  40708. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40709. pp._outputTexture = targetTexture;
  40710. }
  40711. else {
  40712. engine.restoreDefaultFramebuffer();
  40713. pp._outputTexture = null;
  40714. }
  40715. }
  40716. if (doNotPresent) {
  40717. break;
  40718. }
  40719. var effect = pp.apply();
  40720. if (effect) {
  40721. pp.onBeforeRenderObservable.notifyObservers(effect);
  40722. // VBOs
  40723. this._prepareBuffers();
  40724. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40725. // Draw order
  40726. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40727. pp.onAfterRenderObservable.notifyObservers(effect);
  40728. }
  40729. }
  40730. // Restore states
  40731. engine.setDepthBuffer(true);
  40732. engine.setDepthWrite(true);
  40733. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40734. };
  40735. /**
  40736. * Disposes of the post process manager.
  40737. */
  40738. PostProcessManager.prototype.dispose = function () {
  40739. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40740. if (buffer) {
  40741. buffer.dispose();
  40742. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40743. }
  40744. if (this._indexBuffer) {
  40745. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40746. this._indexBuffer = null;
  40747. }
  40748. };
  40749. return PostProcessManager;
  40750. }());
  40751. BABYLON.PostProcessManager = PostProcessManager;
  40752. })(BABYLON || (BABYLON = {}));
  40753. //# sourceMappingURL=babylon.postProcessManager.js.map
  40754. var BABYLON;
  40755. (function (BABYLON) {
  40756. /**
  40757. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40758. */
  40759. var PerformanceMonitor = /** @class */ (function () {
  40760. /**
  40761. * constructor
  40762. * @param frameSampleSize The number of samples required to saturate the sliding window
  40763. */
  40764. function PerformanceMonitor(frameSampleSize) {
  40765. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40766. this._enabled = true;
  40767. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40768. }
  40769. /**
  40770. * Samples current frame
  40771. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40772. */
  40773. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40774. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40775. if (!this._enabled)
  40776. return;
  40777. if (this._lastFrameTimeMs != null) {
  40778. var dt = timeMs - this._lastFrameTimeMs;
  40779. this._rollingFrameTime.add(dt);
  40780. }
  40781. this._lastFrameTimeMs = timeMs;
  40782. };
  40783. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40784. /**
  40785. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40786. * @return Average frame time in milliseconds
  40787. */
  40788. get: function () {
  40789. return this._rollingFrameTime.average;
  40790. },
  40791. enumerable: true,
  40792. configurable: true
  40793. });
  40794. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40795. /**
  40796. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40797. * @return Frame time variance in milliseconds squared
  40798. */
  40799. get: function () {
  40800. return this._rollingFrameTime.variance;
  40801. },
  40802. enumerable: true,
  40803. configurable: true
  40804. });
  40805. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40806. /**
  40807. * Returns the frame time of the most recent frame
  40808. * @return Frame time in milliseconds
  40809. */
  40810. get: function () {
  40811. return this._rollingFrameTime.history(0);
  40812. },
  40813. enumerable: true,
  40814. configurable: true
  40815. });
  40816. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40817. /**
  40818. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40819. * @return Framerate in frames per second
  40820. */
  40821. get: function () {
  40822. return 1000.0 / this._rollingFrameTime.average;
  40823. },
  40824. enumerable: true,
  40825. configurable: true
  40826. });
  40827. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40828. /**
  40829. * Returns the average framerate in frames per second using the most recent frame time
  40830. * @return Framerate in frames per second
  40831. */
  40832. get: function () {
  40833. var history = this._rollingFrameTime.history(0);
  40834. if (history === 0) {
  40835. return 0;
  40836. }
  40837. return 1000.0 / history;
  40838. },
  40839. enumerable: true,
  40840. configurable: true
  40841. });
  40842. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40843. /**
  40844. * Returns true if enough samples have been taken to completely fill the sliding window
  40845. * @return true if saturated
  40846. */
  40847. get: function () {
  40848. return this._rollingFrameTime.isSaturated();
  40849. },
  40850. enumerable: true,
  40851. configurable: true
  40852. });
  40853. /**
  40854. * Enables contributions to the sliding window sample set
  40855. */
  40856. PerformanceMonitor.prototype.enable = function () {
  40857. this._enabled = true;
  40858. };
  40859. /**
  40860. * Disables contributions to the sliding window sample set
  40861. * Samples will not be interpolated over the disabled period
  40862. */
  40863. PerformanceMonitor.prototype.disable = function () {
  40864. this._enabled = false;
  40865. //clear last sample to avoid interpolating over the disabled period when next enabled
  40866. this._lastFrameTimeMs = null;
  40867. };
  40868. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40869. /**
  40870. * Returns true if sampling is enabled
  40871. * @return true if enabled
  40872. */
  40873. get: function () {
  40874. return this._enabled;
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. /**
  40880. * Resets performance monitor
  40881. */
  40882. PerformanceMonitor.prototype.reset = function () {
  40883. //clear last sample to avoid interpolating over the disabled period when next enabled
  40884. this._lastFrameTimeMs = null;
  40885. //wipe record
  40886. this._rollingFrameTime.reset();
  40887. };
  40888. return PerformanceMonitor;
  40889. }());
  40890. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40891. /**
  40892. * RollingAverage
  40893. *
  40894. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40895. */
  40896. var RollingAverage = /** @class */ (function () {
  40897. /**
  40898. * constructor
  40899. * @param length The number of samples required to saturate the sliding window
  40900. */
  40901. function RollingAverage(length) {
  40902. this._samples = new Array(length);
  40903. this.reset();
  40904. }
  40905. /**
  40906. * Adds a sample to the sample set
  40907. * @param v The sample value
  40908. */
  40909. RollingAverage.prototype.add = function (v) {
  40910. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40911. var delta;
  40912. //we need to check if we've already wrapped round
  40913. if (this.isSaturated()) {
  40914. //remove bottom of stack from mean
  40915. var bottomValue = this._samples[this._pos];
  40916. delta = bottomValue - this.average;
  40917. this.average -= delta / (this._sampleCount - 1);
  40918. this._m2 -= delta * (bottomValue - this.average);
  40919. }
  40920. else {
  40921. this._sampleCount++;
  40922. }
  40923. //add new value to mean
  40924. delta = v - this.average;
  40925. this.average += delta / (this._sampleCount);
  40926. this._m2 += delta * (v - this.average);
  40927. //set the new variance
  40928. this.variance = this._m2 / (this._sampleCount - 1);
  40929. this._samples[this._pos] = v;
  40930. this._pos++;
  40931. this._pos %= this._samples.length; //positive wrap around
  40932. };
  40933. /**
  40934. * Returns previously added values or null if outside of history or outside the sliding window domain
  40935. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40936. * @return Value previously recorded with add() or null if outside of range
  40937. */
  40938. RollingAverage.prototype.history = function (i) {
  40939. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40940. return 0;
  40941. }
  40942. var i0 = this._wrapPosition(this._pos - 1.0);
  40943. return this._samples[this._wrapPosition(i0 - i)];
  40944. };
  40945. /**
  40946. * Returns true if enough samples have been taken to completely fill the sliding window
  40947. * @return true if sample-set saturated
  40948. */
  40949. RollingAverage.prototype.isSaturated = function () {
  40950. return this._sampleCount >= this._samples.length;
  40951. };
  40952. /**
  40953. * Resets the rolling average (equivalent to 0 samples taken so far)
  40954. */
  40955. RollingAverage.prototype.reset = function () {
  40956. this.average = 0;
  40957. this.variance = 0;
  40958. this._sampleCount = 0;
  40959. this._pos = 0;
  40960. this._m2 = 0;
  40961. };
  40962. /**
  40963. * Wraps a value around the sample range boundaries
  40964. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40965. * @return Wrapped position in sample range
  40966. */
  40967. RollingAverage.prototype._wrapPosition = function (i) {
  40968. var max = this._samples.length;
  40969. return ((i % max) + max) % max;
  40970. };
  40971. return RollingAverage;
  40972. }());
  40973. BABYLON.RollingAverage = RollingAverage;
  40974. })(BABYLON || (BABYLON = {}));
  40975. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40976. var BABYLON;
  40977. (function (BABYLON) {
  40978. /**
  40979. * This groups together the common properties used for image processing either in direct forward pass
  40980. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40981. * or not.
  40982. */
  40983. var ImageProcessingConfiguration = /** @class */ (function () {
  40984. function ImageProcessingConfiguration() {
  40985. /**
  40986. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40987. */
  40988. this.colorCurves = new BABYLON.ColorCurves();
  40989. this._colorCurvesEnabled = false;
  40990. this._colorGradingEnabled = false;
  40991. this._colorGradingWithGreenDepth = true;
  40992. this._colorGradingBGR = true;
  40993. this._exposure = 1.0;
  40994. this._toneMappingEnabled = false;
  40995. this._contrast = 1.0;
  40996. /**
  40997. * Vignette stretch size.
  40998. */
  40999. this.vignetteStretch = 0;
  41000. /**
  41001. * Vignette centre X Offset.
  41002. */
  41003. this.vignetteCentreX = 0;
  41004. /**
  41005. * Vignette centre Y Offset.
  41006. */
  41007. this.vignetteCentreY = 0;
  41008. /**
  41009. * Vignette weight or intensity of the vignette effect.
  41010. */
  41011. this.vignetteWeight = 1.5;
  41012. /**
  41013. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41014. * if vignetteEnabled is set to true.
  41015. */
  41016. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41017. /**
  41018. * Camera field of view used by the Vignette effect.
  41019. */
  41020. this.vignetteCameraFov = 0.5;
  41021. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41022. this._vignetteEnabled = false;
  41023. this._applyByPostProcess = false;
  41024. this._isEnabled = true;
  41025. /**
  41026. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41027. */
  41028. this.onUpdateParameters = new BABYLON.Observable();
  41029. }
  41030. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41031. /**
  41032. * Gets wether the color curves effect is enabled.
  41033. */
  41034. get: function () {
  41035. return this._colorCurvesEnabled;
  41036. },
  41037. /**
  41038. * Sets wether the color curves effect is enabled.
  41039. */
  41040. set: function (value) {
  41041. if (this._colorCurvesEnabled === value) {
  41042. return;
  41043. }
  41044. this._colorCurvesEnabled = value;
  41045. this._updateParameters();
  41046. },
  41047. enumerable: true,
  41048. configurable: true
  41049. });
  41050. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41051. /**
  41052. * Gets wether the color grading effect is enabled.
  41053. */
  41054. get: function () {
  41055. return this._colorGradingEnabled;
  41056. },
  41057. /**
  41058. * Sets wether the color grading effect is enabled.
  41059. */
  41060. set: function (value) {
  41061. if (this._colorGradingEnabled === value) {
  41062. return;
  41063. }
  41064. this._colorGradingEnabled = value;
  41065. this._updateParameters();
  41066. },
  41067. enumerable: true,
  41068. configurable: true
  41069. });
  41070. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41071. /**
  41072. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41073. */
  41074. get: function () {
  41075. return this._colorGradingWithGreenDepth;
  41076. },
  41077. /**
  41078. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41079. */
  41080. set: function (value) {
  41081. if (this._colorGradingWithGreenDepth === value) {
  41082. return;
  41083. }
  41084. this._colorGradingWithGreenDepth = value;
  41085. this._updateParameters();
  41086. },
  41087. enumerable: true,
  41088. configurable: true
  41089. });
  41090. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41091. /**
  41092. * Gets wether the color grading texture contains BGR values.
  41093. */
  41094. get: function () {
  41095. return this._colorGradingBGR;
  41096. },
  41097. /**
  41098. * Sets wether the color grading texture contains BGR values.
  41099. */
  41100. set: function (value) {
  41101. if (this._colorGradingBGR === value) {
  41102. return;
  41103. }
  41104. this._colorGradingBGR = value;
  41105. this._updateParameters();
  41106. },
  41107. enumerable: true,
  41108. configurable: true
  41109. });
  41110. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41111. /**
  41112. * Gets the Exposure used in the effect.
  41113. */
  41114. get: function () {
  41115. return this._exposure;
  41116. },
  41117. /**
  41118. * Sets the Exposure used in the effect.
  41119. */
  41120. set: function (value) {
  41121. if (this._exposure === value) {
  41122. return;
  41123. }
  41124. this._exposure = value;
  41125. this._updateParameters();
  41126. },
  41127. enumerable: true,
  41128. configurable: true
  41129. });
  41130. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41131. /**
  41132. * Gets wether the tone mapping effect is enabled.
  41133. */
  41134. get: function () {
  41135. return this._toneMappingEnabled;
  41136. },
  41137. /**
  41138. * Sets wether the tone mapping effect is enabled.
  41139. */
  41140. set: function (value) {
  41141. if (this._toneMappingEnabled === value) {
  41142. return;
  41143. }
  41144. this._toneMappingEnabled = value;
  41145. this._updateParameters();
  41146. },
  41147. enumerable: true,
  41148. configurable: true
  41149. });
  41150. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41151. /**
  41152. * Gets the contrast used in the effect.
  41153. */
  41154. get: function () {
  41155. return this._contrast;
  41156. },
  41157. /**
  41158. * Sets the contrast used in the effect.
  41159. */
  41160. set: function (value) {
  41161. if (this._contrast === value) {
  41162. return;
  41163. }
  41164. this._contrast = value;
  41165. this._updateParameters();
  41166. },
  41167. enumerable: true,
  41168. configurable: true
  41169. });
  41170. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41171. /**
  41172. * Gets the vignette blend mode allowing different kind of effect.
  41173. */
  41174. get: function () {
  41175. return this._vignetteBlendMode;
  41176. },
  41177. /**
  41178. * Sets the vignette blend mode allowing different kind of effect.
  41179. */
  41180. set: function (value) {
  41181. if (this._vignetteBlendMode === value) {
  41182. return;
  41183. }
  41184. this._vignetteBlendMode = value;
  41185. this._updateParameters();
  41186. },
  41187. enumerable: true,
  41188. configurable: true
  41189. });
  41190. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41191. /**
  41192. * Gets wether the vignette effect is enabled.
  41193. */
  41194. get: function () {
  41195. return this._vignetteEnabled;
  41196. },
  41197. /**
  41198. * Sets wether the vignette effect is enabled.
  41199. */
  41200. set: function (value) {
  41201. if (this._vignetteEnabled === value) {
  41202. return;
  41203. }
  41204. this._vignetteEnabled = value;
  41205. this._updateParameters();
  41206. },
  41207. enumerable: true,
  41208. configurable: true
  41209. });
  41210. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41211. /**
  41212. * Gets wether the image processing is applied through a post process or not.
  41213. */
  41214. get: function () {
  41215. return this._applyByPostProcess;
  41216. },
  41217. /**
  41218. * Sets wether the image processing is applied through a post process or not.
  41219. */
  41220. set: function (value) {
  41221. if (this._applyByPostProcess === value) {
  41222. return;
  41223. }
  41224. this._applyByPostProcess = value;
  41225. this._updateParameters();
  41226. },
  41227. enumerable: true,
  41228. configurable: true
  41229. });
  41230. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41231. /**
  41232. * Gets wether the image processing is enabled or not.
  41233. */
  41234. get: function () {
  41235. return this._isEnabled;
  41236. },
  41237. /**
  41238. * Sets wether the image processing is enabled or not.
  41239. */
  41240. set: function (value) {
  41241. if (this._isEnabled === value) {
  41242. return;
  41243. }
  41244. this._isEnabled = value;
  41245. this._updateParameters();
  41246. },
  41247. enumerable: true,
  41248. configurable: true
  41249. });
  41250. /**
  41251. * Method called each time the image processing information changes requires to recompile the effect.
  41252. */
  41253. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41254. this.onUpdateParameters.notifyObservers(this);
  41255. };
  41256. ImageProcessingConfiguration.prototype.getClassName = function () {
  41257. return "ImageProcessingConfiguration";
  41258. };
  41259. /**
  41260. * Prepare the list of uniforms associated with the Image Processing effects.
  41261. * @param uniformsList The list of uniforms used in the effect
  41262. * @param defines the list of defines currently in use
  41263. */
  41264. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41265. if (defines.EXPOSURE) {
  41266. uniforms.push("exposureLinear");
  41267. }
  41268. if (defines.CONTRAST) {
  41269. uniforms.push("contrast");
  41270. }
  41271. if (defines.COLORGRADING) {
  41272. uniforms.push("colorTransformSettings");
  41273. }
  41274. if (defines.VIGNETTE) {
  41275. uniforms.push("vInverseScreenSize");
  41276. uniforms.push("vignetteSettings1");
  41277. uniforms.push("vignetteSettings2");
  41278. }
  41279. if (defines.COLORCURVES) {
  41280. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41281. }
  41282. };
  41283. /**
  41284. * Prepare the list of samplers associated with the Image Processing effects.
  41285. * @param uniformsList The list of uniforms used in the effect
  41286. * @param defines the list of defines currently in use
  41287. */
  41288. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41289. if (defines.COLORGRADING) {
  41290. samplersList.push("txColorTransform");
  41291. }
  41292. };
  41293. /**
  41294. * Prepare the list of defines associated to the shader.
  41295. * @param defines the list of defines to complete
  41296. */
  41297. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41298. if (forPostProcess === void 0) { forPostProcess = false; }
  41299. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41300. defines.VIGNETTE = false;
  41301. defines.TONEMAPPING = false;
  41302. defines.CONTRAST = false;
  41303. defines.EXPOSURE = false;
  41304. defines.COLORCURVES = false;
  41305. defines.COLORGRADING = false;
  41306. defines.COLORGRADING3D = false;
  41307. defines.IMAGEPROCESSING = false;
  41308. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41309. return;
  41310. }
  41311. defines.VIGNETTE = this.vignetteEnabled;
  41312. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41313. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41314. defines.TONEMAPPING = this.toneMappingEnabled;
  41315. defines.CONTRAST = (this.contrast !== 1.0);
  41316. defines.EXPOSURE = (this.exposure !== 1.0);
  41317. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41318. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41319. if (defines.COLORGRADING) {
  41320. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41321. }
  41322. else {
  41323. defines.COLORGRADING3D = false;
  41324. }
  41325. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41326. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41327. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41328. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41329. };
  41330. /**
  41331. * Returns true if all the image processing information are ready.
  41332. */
  41333. ImageProcessingConfiguration.prototype.isReady = function () {
  41334. // Color Grading texure can not be none blocking.
  41335. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41336. };
  41337. /**
  41338. * Binds the image processing to the shader.
  41339. * @param effect The effect to bind to
  41340. */
  41341. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41342. if (aspectRatio === void 0) { aspectRatio = 1; }
  41343. // Color Curves
  41344. if (this._colorCurvesEnabled && this.colorCurves) {
  41345. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41346. }
  41347. // Vignette
  41348. if (this._vignetteEnabled) {
  41349. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41350. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41351. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41352. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41353. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41354. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41355. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41356. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41357. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41358. var vignettePower = -2.0 * this.vignetteWeight;
  41359. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41360. }
  41361. // Exposure
  41362. effect.setFloat("exposureLinear", this.exposure);
  41363. // Contrast
  41364. effect.setFloat("contrast", this.contrast);
  41365. // Color transform settings
  41366. if (this.colorGradingTexture) {
  41367. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41368. var textureSize = this.colorGradingTexture.getSize().height;
  41369. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41370. 0.5 / textureSize, // textureOffset
  41371. textureSize, // textureSize
  41372. this.colorGradingTexture.level // weight
  41373. );
  41374. }
  41375. };
  41376. /**
  41377. * Clones the current image processing instance.
  41378. * @return The cloned image processing
  41379. */
  41380. ImageProcessingConfiguration.prototype.clone = function () {
  41381. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41382. };
  41383. /**
  41384. * Serializes the current image processing instance to a json representation.
  41385. * @return a JSON representation
  41386. */
  41387. ImageProcessingConfiguration.prototype.serialize = function () {
  41388. return BABYLON.SerializationHelper.Serialize(this);
  41389. };
  41390. /**
  41391. * Parses the image processing from a json representation.
  41392. * @param source the JSON source to parse
  41393. * @return The parsed image processing
  41394. */
  41395. ImageProcessingConfiguration.Parse = function (source) {
  41396. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41397. };
  41398. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41399. /**
  41400. * Used to apply the vignette as a mix with the pixel color.
  41401. */
  41402. get: function () {
  41403. return this._VIGNETTEMODE_MULTIPLY;
  41404. },
  41405. enumerable: true,
  41406. configurable: true
  41407. });
  41408. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41409. /**
  41410. * Used to apply the vignette as a replacement of the pixel color.
  41411. */
  41412. get: function () {
  41413. return this._VIGNETTEMODE_OPAQUE;
  41414. },
  41415. enumerable: true,
  41416. configurable: true
  41417. });
  41418. // Static constants associated to the image processing.
  41419. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41420. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41421. __decorate([
  41422. BABYLON.serializeAsColorCurves()
  41423. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41424. __decorate([
  41425. BABYLON.serialize()
  41426. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41427. __decorate([
  41428. BABYLON.serializeAsTexture()
  41429. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41430. __decorate([
  41431. BABYLON.serialize()
  41432. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41433. __decorate([
  41434. BABYLON.serialize()
  41435. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41436. __decorate([
  41437. BABYLON.serialize()
  41438. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41439. __decorate([
  41440. BABYLON.serialize()
  41441. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41442. __decorate([
  41443. BABYLON.serialize()
  41444. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41445. __decorate([
  41446. BABYLON.serialize()
  41447. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41448. __decorate([
  41449. BABYLON.serialize()
  41450. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41451. __decorate([
  41452. BABYLON.serialize()
  41453. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41454. __decorate([
  41455. BABYLON.serialize()
  41456. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41457. __decorate([
  41458. BABYLON.serialize()
  41459. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41460. __decorate([
  41461. BABYLON.serializeAsColor4()
  41462. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41463. __decorate([
  41464. BABYLON.serialize()
  41465. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41466. __decorate([
  41467. BABYLON.serialize()
  41468. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41469. __decorate([
  41470. BABYLON.serialize()
  41471. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41472. __decorate([
  41473. BABYLON.serialize()
  41474. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41475. __decorate([
  41476. BABYLON.serialize()
  41477. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41478. return ImageProcessingConfiguration;
  41479. }());
  41480. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41481. })(BABYLON || (BABYLON = {}));
  41482. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41483. var BABYLON;
  41484. (function (BABYLON) {
  41485. /**
  41486. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41487. * It can help converting any input color in a desired output one. This can then be used to create effects
  41488. * from sepia, black and white to sixties or futuristic rendering...
  41489. *
  41490. * The only supported format is currently 3dl.
  41491. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41492. */
  41493. var ColorGradingTexture = /** @class */ (function (_super) {
  41494. __extends(ColorGradingTexture, _super);
  41495. /**
  41496. * Instantiates a ColorGradingTexture from the following parameters.
  41497. *
  41498. * @param url The location of the color gradind data (currently only supporting 3dl)
  41499. * @param scene The scene the texture will be used in
  41500. */
  41501. function ColorGradingTexture(url, scene) {
  41502. var _this = _super.call(this, scene) || this;
  41503. if (!url) {
  41504. return _this;
  41505. }
  41506. _this._engine = scene.getEngine();
  41507. _this._textureMatrix = BABYLON.Matrix.Identity();
  41508. _this.name = url;
  41509. _this.url = url;
  41510. _this.hasAlpha = false;
  41511. _this.isCube = false;
  41512. _this.is3D = _this._engine.webGLVersion > 1;
  41513. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41514. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41515. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41516. _this.anisotropicFilteringLevel = 1;
  41517. _this._texture = _this._getFromCache(url, true);
  41518. if (!_this._texture) {
  41519. if (!scene.useDelayedTextureLoading) {
  41520. _this.loadTexture();
  41521. }
  41522. else {
  41523. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41524. }
  41525. }
  41526. return _this;
  41527. }
  41528. /**
  41529. * Returns the texture matrix used in most of the material.
  41530. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41531. */
  41532. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41533. return this._textureMatrix;
  41534. };
  41535. /**
  41536. * Occurs when the file being loaded is a .3dl LUT file.
  41537. */
  41538. ColorGradingTexture.prototype.load3dlTexture = function () {
  41539. var engine = this._engine;
  41540. var texture;
  41541. if (engine.webGLVersion === 1) {
  41542. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41543. }
  41544. else {
  41545. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41546. }
  41547. this._texture = texture;
  41548. var callback = function (text) {
  41549. if (typeof text !== "string") {
  41550. return;
  41551. }
  41552. var data = null;
  41553. var tempData = null;
  41554. var line;
  41555. var lines = text.split('\n');
  41556. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41557. var maxColor = 0;
  41558. for (var i = 0; i < lines.length; i++) {
  41559. line = lines[i];
  41560. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41561. continue;
  41562. if (line.indexOf('#') === 0)
  41563. continue;
  41564. var words = line.split(" ");
  41565. if (size === 0) {
  41566. // Number of space + one
  41567. size = words.length;
  41568. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41569. tempData = new Float32Array(size * size * size * 4);
  41570. continue;
  41571. }
  41572. if (size != 0) {
  41573. var r = Math.max(parseInt(words[0]), 0);
  41574. var g = Math.max(parseInt(words[1]), 0);
  41575. var b = Math.max(parseInt(words[2]), 0);
  41576. maxColor = Math.max(r, maxColor);
  41577. maxColor = Math.max(g, maxColor);
  41578. maxColor = Math.max(b, maxColor);
  41579. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41580. if (tempData) {
  41581. tempData[pixelStorageIndex + 0] = r;
  41582. tempData[pixelStorageIndex + 1] = g;
  41583. tempData[pixelStorageIndex + 2] = b;
  41584. }
  41585. pixelIndexSlice++;
  41586. if (pixelIndexSlice % size == 0) {
  41587. pixelIndexH++;
  41588. pixelIndexSlice = 0;
  41589. if (pixelIndexH % size == 0) {
  41590. pixelIndexW++;
  41591. pixelIndexH = 0;
  41592. }
  41593. }
  41594. }
  41595. }
  41596. if (tempData && data) {
  41597. for (var i = 0; i < tempData.length; i++) {
  41598. if (i > 0 && (i + 1) % 4 === 0) {
  41599. data[i] = 255;
  41600. }
  41601. else {
  41602. var value = tempData[i];
  41603. data[i] = (value / maxColor * 255);
  41604. }
  41605. }
  41606. }
  41607. if (texture.is3D) {
  41608. texture.updateSize(size, size, size);
  41609. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41610. }
  41611. else {
  41612. texture.updateSize(size * size, size);
  41613. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41614. }
  41615. };
  41616. var scene = this.getScene();
  41617. if (scene) {
  41618. scene._loadFile(this.url, callback);
  41619. }
  41620. else {
  41621. this._engine._loadFile(this.url, callback);
  41622. }
  41623. return this._texture;
  41624. };
  41625. /**
  41626. * Starts the loading process of the texture.
  41627. */
  41628. ColorGradingTexture.prototype.loadTexture = function () {
  41629. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41630. this.load3dlTexture();
  41631. }
  41632. };
  41633. /**
  41634. * Clones the color gradind texture.
  41635. */
  41636. ColorGradingTexture.prototype.clone = function () {
  41637. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41638. // Base texture
  41639. newTexture.level = this.level;
  41640. return newTexture;
  41641. };
  41642. /**
  41643. * Called during delayed load for textures.
  41644. */
  41645. ColorGradingTexture.prototype.delayLoad = function () {
  41646. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41647. return;
  41648. }
  41649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41650. this._texture = this._getFromCache(this.url, true);
  41651. if (!this._texture) {
  41652. this.loadTexture();
  41653. }
  41654. };
  41655. /**
  41656. * Parses a color grading texture serialized by Babylon.
  41657. * @param parsedTexture The texture information being parsedTexture
  41658. * @param scene The scene to load the texture in
  41659. * @param rootUrl The root url of the data assets to load
  41660. * @return A color gradind texture
  41661. */
  41662. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41663. var texture = null;
  41664. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41665. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41666. texture.name = parsedTexture.name;
  41667. texture.level = parsedTexture.level;
  41668. }
  41669. return texture;
  41670. };
  41671. /**
  41672. * Serializes the LUT texture to json format.
  41673. */
  41674. ColorGradingTexture.prototype.serialize = function () {
  41675. if (!this.name) {
  41676. return null;
  41677. }
  41678. var serializationObject = {};
  41679. serializationObject.name = this.name;
  41680. serializationObject.level = this.level;
  41681. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41682. return serializationObject;
  41683. };
  41684. /**
  41685. * Empty line regex stored for GC.
  41686. */
  41687. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41688. return ColorGradingTexture;
  41689. }(BABYLON.BaseTexture));
  41690. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41691. })(BABYLON || (BABYLON = {}));
  41692. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41693. var BABYLON;
  41694. (function (BABYLON) {
  41695. /**
  41696. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41697. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41698. * 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;
  41699. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41700. */
  41701. var ColorCurves = /** @class */ (function () {
  41702. function ColorCurves() {
  41703. this._dirty = true;
  41704. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41705. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41706. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41707. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41708. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41709. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41710. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41711. this._globalHue = 30;
  41712. this._globalDensity = 0;
  41713. this._globalSaturation = 0;
  41714. this._globalExposure = 0;
  41715. this._highlightsHue = 30;
  41716. this._highlightsDensity = 0;
  41717. this._highlightsSaturation = 0;
  41718. this._highlightsExposure = 0;
  41719. this._midtonesHue = 30;
  41720. this._midtonesDensity = 0;
  41721. this._midtonesSaturation = 0;
  41722. this._midtonesExposure = 0;
  41723. this._shadowsHue = 30;
  41724. this._shadowsDensity = 0;
  41725. this._shadowsSaturation = 0;
  41726. this._shadowsExposure = 0;
  41727. }
  41728. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41729. /**
  41730. * Gets the global Hue value.
  41731. * 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).
  41732. */
  41733. get: function () {
  41734. return this._globalHue;
  41735. },
  41736. /**
  41737. * Sets the global Hue value.
  41738. * 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).
  41739. */
  41740. set: function (value) {
  41741. this._globalHue = value;
  41742. this._dirty = true;
  41743. },
  41744. enumerable: true,
  41745. configurable: true
  41746. });
  41747. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41748. /**
  41749. * Gets the global Density value.
  41750. * 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.
  41751. * Values less than zero provide a filter of opposite hue.
  41752. */
  41753. get: function () {
  41754. return this._globalDensity;
  41755. },
  41756. /**
  41757. * Sets the global Density value.
  41758. * 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.
  41759. * Values less than zero provide a filter of opposite hue.
  41760. */
  41761. set: function (value) {
  41762. this._globalDensity = value;
  41763. this._dirty = true;
  41764. },
  41765. enumerable: true,
  41766. configurable: true
  41767. });
  41768. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41769. /**
  41770. * Gets the global Saturation value.
  41771. * 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.
  41772. */
  41773. get: function () {
  41774. return this._globalSaturation;
  41775. },
  41776. /**
  41777. * Sets the global Saturation value.
  41778. * 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.
  41779. */
  41780. set: function (value) {
  41781. this._globalSaturation = value;
  41782. this._dirty = true;
  41783. },
  41784. enumerable: true,
  41785. configurable: true
  41786. });
  41787. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41788. /**
  41789. * Gets the highlights Hue value.
  41790. * 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).
  41791. */
  41792. get: function () {
  41793. return this._highlightsHue;
  41794. },
  41795. /**
  41796. * Sets the highlights Hue value.
  41797. * 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).
  41798. */
  41799. set: function (value) {
  41800. this._highlightsHue = value;
  41801. this._dirty = true;
  41802. },
  41803. enumerable: true,
  41804. configurable: true
  41805. });
  41806. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41807. /**
  41808. * Gets the highlights Density value.
  41809. * 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.
  41810. * Values less than zero provide a filter of opposite hue.
  41811. */
  41812. get: function () {
  41813. return this._highlightsDensity;
  41814. },
  41815. /**
  41816. * Sets the highlights Density value.
  41817. * 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.
  41818. * Values less than zero provide a filter of opposite hue.
  41819. */
  41820. set: function (value) {
  41821. this._highlightsDensity = value;
  41822. this._dirty = true;
  41823. },
  41824. enumerable: true,
  41825. configurable: true
  41826. });
  41827. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41828. /**
  41829. * Gets the highlights Saturation value.
  41830. * 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.
  41831. */
  41832. get: function () {
  41833. return this._highlightsSaturation;
  41834. },
  41835. /**
  41836. * Sets the highlights Saturation value.
  41837. * 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.
  41838. */
  41839. set: function (value) {
  41840. this._highlightsSaturation = value;
  41841. this._dirty = true;
  41842. },
  41843. enumerable: true,
  41844. configurable: true
  41845. });
  41846. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41847. /**
  41848. * Gets the highlights Exposure value.
  41849. * 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.
  41850. */
  41851. get: function () {
  41852. return this._highlightsExposure;
  41853. },
  41854. /**
  41855. * Sets the highlights Exposure value.
  41856. * 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.
  41857. */
  41858. set: function (value) {
  41859. this._highlightsExposure = value;
  41860. this._dirty = true;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41866. /**
  41867. * Gets the midtones Hue value.
  41868. * 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).
  41869. */
  41870. get: function () {
  41871. return this._midtonesHue;
  41872. },
  41873. /**
  41874. * Sets the midtones Hue value.
  41875. * 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).
  41876. */
  41877. set: function (value) {
  41878. this._midtonesHue = value;
  41879. this._dirty = true;
  41880. },
  41881. enumerable: true,
  41882. configurable: true
  41883. });
  41884. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41885. /**
  41886. * Gets the midtones Density value.
  41887. * 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.
  41888. * Values less than zero provide a filter of opposite hue.
  41889. */
  41890. get: function () {
  41891. return this._midtonesDensity;
  41892. },
  41893. /**
  41894. * Sets the midtones Density value.
  41895. * 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.
  41896. * Values less than zero provide a filter of opposite hue.
  41897. */
  41898. set: function (value) {
  41899. this._midtonesDensity = value;
  41900. this._dirty = true;
  41901. },
  41902. enumerable: true,
  41903. configurable: true
  41904. });
  41905. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41906. /**
  41907. * Gets the midtones Saturation value.
  41908. * 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.
  41909. */
  41910. get: function () {
  41911. return this._midtonesSaturation;
  41912. },
  41913. /**
  41914. * Sets the midtones Saturation value.
  41915. * 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.
  41916. */
  41917. set: function (value) {
  41918. this._midtonesSaturation = value;
  41919. this._dirty = true;
  41920. },
  41921. enumerable: true,
  41922. configurable: true
  41923. });
  41924. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41925. /**
  41926. * Gets the midtones Exposure value.
  41927. * 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.
  41928. */
  41929. get: function () {
  41930. return this._midtonesExposure;
  41931. },
  41932. /**
  41933. * Sets the midtones Exposure value.
  41934. * 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.
  41935. */
  41936. set: function (value) {
  41937. this._midtonesExposure = value;
  41938. this._dirty = true;
  41939. },
  41940. enumerable: true,
  41941. configurable: true
  41942. });
  41943. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41944. /**
  41945. * Gets the shadows Hue value.
  41946. * 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).
  41947. */
  41948. get: function () {
  41949. return this._shadowsHue;
  41950. },
  41951. /**
  41952. * Sets the shadows Hue value.
  41953. * 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).
  41954. */
  41955. set: function (value) {
  41956. this._shadowsHue = value;
  41957. this._dirty = true;
  41958. },
  41959. enumerable: true,
  41960. configurable: true
  41961. });
  41962. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41963. /**
  41964. * Gets the shadows Density value.
  41965. * 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.
  41966. * Values less than zero provide a filter of opposite hue.
  41967. */
  41968. get: function () {
  41969. return this._shadowsDensity;
  41970. },
  41971. /**
  41972. * Sets the shadows Density value.
  41973. * 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.
  41974. * Values less than zero provide a filter of opposite hue.
  41975. */
  41976. set: function (value) {
  41977. this._shadowsDensity = value;
  41978. this._dirty = true;
  41979. },
  41980. enumerable: true,
  41981. configurable: true
  41982. });
  41983. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41984. /**
  41985. * Gets the shadows Saturation value.
  41986. * 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.
  41987. */
  41988. get: function () {
  41989. return this._shadowsSaturation;
  41990. },
  41991. /**
  41992. * Sets the shadows Saturation value.
  41993. * 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.
  41994. */
  41995. set: function (value) {
  41996. this._shadowsSaturation = value;
  41997. this._dirty = true;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42003. /**
  42004. * Gets the shadows Exposure value.
  42005. * 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.
  42006. */
  42007. get: function () {
  42008. return this._shadowsExposure;
  42009. },
  42010. /**
  42011. * Sets the shadows Exposure value.
  42012. * 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.
  42013. */
  42014. set: function (value) {
  42015. this._shadowsExposure = value;
  42016. this._dirty = true;
  42017. },
  42018. enumerable: true,
  42019. configurable: true
  42020. });
  42021. ColorCurves.prototype.getClassName = function () {
  42022. return "ColorCurves";
  42023. };
  42024. /**
  42025. * Binds the color curves to the shader.
  42026. * @param colorCurves The color curve to bind
  42027. * @param effect The effect to bind to
  42028. */
  42029. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42030. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42031. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42032. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42033. if (colorCurves._dirty) {
  42034. colorCurves._dirty = false;
  42035. // Fill in global info.
  42036. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42037. // Compute highlights info.
  42038. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42039. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42040. // Compute midtones info.
  42041. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42042. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42043. // Compute shadows info.
  42044. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42045. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42046. // Compute deltas (neutral is midtones).
  42047. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42048. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42049. }
  42050. if (effect) {
  42051. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42052. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42053. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42054. }
  42055. };
  42056. /**
  42057. * Prepare the list of uniforms associated with the ColorCurves effects.
  42058. * @param uniformsList The list of uniforms used in the effect
  42059. */
  42060. ColorCurves.PrepareUniforms = function (uniformsList) {
  42061. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42062. };
  42063. /**
  42064. * Returns color grading data based on a hue, density, saturation and exposure value.
  42065. * @param filterHue The hue of the color filter.
  42066. * @param filterDensity The density of the color filter.
  42067. * @param saturation The saturation.
  42068. * @param exposure The exposure.
  42069. * @param result The result data container.
  42070. */
  42071. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42072. if (hue == null) {
  42073. return;
  42074. }
  42075. hue = ColorCurves.clamp(hue, 0, 360);
  42076. density = ColorCurves.clamp(density, -100, 100);
  42077. saturation = ColorCurves.clamp(saturation, -100, 100);
  42078. exposure = ColorCurves.clamp(exposure, -100, 100);
  42079. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42080. // so that the maximum filter density is only 50% control. This provides fine control
  42081. // for small values and reasonable range.
  42082. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42083. density *= 0.5;
  42084. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42085. if (density < 0) {
  42086. density *= -1;
  42087. hue = (hue + 180) % 360;
  42088. }
  42089. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42090. result.scaleToRef(2, result);
  42091. result.a = 1 + 0.01 * saturation;
  42092. };
  42093. /**
  42094. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42095. * @param value The input slider value in range [-100,100].
  42096. * @returns Adjusted value.
  42097. */
  42098. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42099. value /= 100;
  42100. var x = Math.abs(value);
  42101. x = Math.pow(x, 2);
  42102. if (value < 0) {
  42103. x *= -1;
  42104. }
  42105. x *= 100;
  42106. return x;
  42107. };
  42108. /**
  42109. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42110. * @param hue The hue (H) input.
  42111. * @param saturation The saturation (S) input.
  42112. * @param brightness The brightness (B) input.
  42113. * @result An RGBA color represented as Vector4.
  42114. */
  42115. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42116. var h = ColorCurves.clamp(hue, 0, 360);
  42117. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42118. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42119. if (s === 0) {
  42120. result.r = v;
  42121. result.g = v;
  42122. result.b = v;
  42123. }
  42124. else {
  42125. // sector 0 to 5
  42126. h /= 60;
  42127. var i = Math.floor(h);
  42128. // fractional part of h
  42129. var f = h - i;
  42130. var p = v * (1 - s);
  42131. var q = v * (1 - s * f);
  42132. var t = v * (1 - s * (1 - f));
  42133. switch (i) {
  42134. case 0:
  42135. result.r = v;
  42136. result.g = t;
  42137. result.b = p;
  42138. break;
  42139. case 1:
  42140. result.r = q;
  42141. result.g = v;
  42142. result.b = p;
  42143. break;
  42144. case 2:
  42145. result.r = p;
  42146. result.g = v;
  42147. result.b = t;
  42148. break;
  42149. case 3:
  42150. result.r = p;
  42151. result.g = q;
  42152. result.b = v;
  42153. break;
  42154. case 4:
  42155. result.r = t;
  42156. result.g = p;
  42157. result.b = v;
  42158. break;
  42159. default: // case 5:
  42160. result.r = v;
  42161. result.g = p;
  42162. result.b = q;
  42163. break;
  42164. }
  42165. }
  42166. result.a = 1;
  42167. };
  42168. /**
  42169. * Returns a value clamped between min and max
  42170. * @param value The value to clamp
  42171. * @param min The minimum of value
  42172. * @param max The maximum of value
  42173. * @returns The clamped value.
  42174. */
  42175. ColorCurves.clamp = function (value, min, max) {
  42176. return Math.min(Math.max(value, min), max);
  42177. };
  42178. /**
  42179. * Clones the current color curve instance.
  42180. * @return The cloned curves
  42181. */
  42182. ColorCurves.prototype.clone = function () {
  42183. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42184. };
  42185. /**
  42186. * Serializes the current color curve instance to a json representation.
  42187. * @return a JSON representation
  42188. */
  42189. ColorCurves.prototype.serialize = function () {
  42190. return BABYLON.SerializationHelper.Serialize(this);
  42191. };
  42192. /**
  42193. * Parses the color curve from a json representation.
  42194. * @param source the JSON source to parse
  42195. * @return The parsed curves
  42196. */
  42197. ColorCurves.Parse = function (source) {
  42198. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42199. };
  42200. __decorate([
  42201. BABYLON.serialize()
  42202. ], ColorCurves.prototype, "_globalHue", void 0);
  42203. __decorate([
  42204. BABYLON.serialize()
  42205. ], ColorCurves.prototype, "_globalDensity", void 0);
  42206. __decorate([
  42207. BABYLON.serialize()
  42208. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42209. __decorate([
  42210. BABYLON.serialize()
  42211. ], ColorCurves.prototype, "_globalExposure", void 0);
  42212. __decorate([
  42213. BABYLON.serialize()
  42214. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42215. __decorate([
  42216. BABYLON.serialize()
  42217. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42218. __decorate([
  42219. BABYLON.serialize()
  42220. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42221. __decorate([
  42222. BABYLON.serialize()
  42223. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42224. __decorate([
  42225. BABYLON.serialize()
  42226. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42227. __decorate([
  42228. BABYLON.serialize()
  42229. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42230. __decorate([
  42231. BABYLON.serialize()
  42232. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42233. __decorate([
  42234. BABYLON.serialize()
  42235. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42236. return ColorCurves;
  42237. }());
  42238. BABYLON.ColorCurves = ColorCurves;
  42239. })(BABYLON || (BABYLON = {}));
  42240. //# sourceMappingURL=babylon.colorCurves.js.map
  42241. //# sourceMappingURL=babylon.behavior.js.map
  42242. var BABYLON;
  42243. (function (BABYLON) {
  42244. /**
  42245. * "Static Class" containing the most commonly used helper while dealing with material for
  42246. * rendering purpose.
  42247. *
  42248. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42249. *
  42250. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42251. */
  42252. var MaterialHelper = /** @class */ (function () {
  42253. function MaterialHelper() {
  42254. }
  42255. /**
  42256. * Bind the current view position to an effect.
  42257. * @param effect The effect to be bound
  42258. * @param scene The scene the eyes position is used from
  42259. */
  42260. MaterialHelper.BindEyePosition = function (effect, scene) {
  42261. if (scene._forcedViewPosition) {
  42262. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42263. return;
  42264. }
  42265. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42266. };
  42267. /**
  42268. * Helps preparing the defines values about the UVs in used in the effect.
  42269. * UVs are shared as much as we can accross chanels in the shaders.
  42270. * @param texture The texture we are preparing the UVs for
  42271. * @param defines The defines to update
  42272. * @param key The chanel key "diffuse", "specular"... used in the shader
  42273. */
  42274. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42275. defines._needUVs = true;
  42276. defines[key] = true;
  42277. if (texture.getTextureMatrix().isIdentity(true)) {
  42278. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42279. if (texture.coordinatesIndex === 0) {
  42280. defines["MAINUV1"] = true;
  42281. }
  42282. else {
  42283. defines["MAINUV2"] = true;
  42284. }
  42285. }
  42286. else {
  42287. defines[key + "DIRECTUV"] = 0;
  42288. }
  42289. };
  42290. /**
  42291. * Binds a texture matrix value to its corrsponding uniform
  42292. * @param texture The texture to bind the matrix for
  42293. * @param uniformBuffer The uniform buffer receivin the data
  42294. * @param key The chanel key "diffuse", "specular"... used in the shader
  42295. */
  42296. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42297. var matrix = texture.getTextureMatrix();
  42298. if (!matrix.isIdentity(true)) {
  42299. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42300. }
  42301. };
  42302. /**
  42303. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42304. * @param mesh defines the current mesh
  42305. * @param scene defines the current scene
  42306. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42307. * @param pointsCloud defines if point cloud rendering has to be turned on
  42308. * @param fogEnabled defines if fog has to be turned on
  42309. * @param alphaTest defines if alpha testing has to be turned on
  42310. * @param defines defines the current list of defines
  42311. */
  42312. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42313. if (defines._areMiscDirty) {
  42314. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42315. defines["POINTSIZE"] = pointsCloud;
  42316. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42317. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42318. defines["ALPHATEST"] = alphaTest;
  42319. }
  42320. };
  42321. /**
  42322. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42323. * @param scene defines the current scene
  42324. * @param engine defines the current engine
  42325. * @param defines specifies the list of active defines
  42326. * @param useInstances defines if instances have to be turned on
  42327. * @param useClipPlane defines if clip plane have to be turned on
  42328. */
  42329. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42330. if (useClipPlane === void 0) { useClipPlane = null; }
  42331. var changed = false;
  42332. if (useClipPlane == null) {
  42333. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42334. }
  42335. if (defines["CLIPPLANE"] !== useClipPlane) {
  42336. defines["CLIPPLANE"] = useClipPlane;
  42337. changed = true;
  42338. }
  42339. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42340. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42341. changed = true;
  42342. }
  42343. if (defines["INSTANCES"] !== useInstances) {
  42344. defines["INSTANCES"] = useInstances;
  42345. changed = true;
  42346. }
  42347. if (changed) {
  42348. defines.markAsUnprocessed();
  42349. }
  42350. };
  42351. /**
  42352. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42353. * @param mesh The mesh containing the geometry data we will draw
  42354. * @param defines The defines to update
  42355. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42356. * @param useBones Precise whether bones should be used or not (override mesh info)
  42357. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42358. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42359. * @returns false if defines are considered not dirty and have not been checked
  42360. */
  42361. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42362. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42363. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42364. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42365. return false;
  42366. }
  42367. defines._normals = defines._needNormals;
  42368. defines._uvs = defines._needUVs;
  42369. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42370. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42371. defines["TANGENT"] = true;
  42372. }
  42373. if (defines._needUVs) {
  42374. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42375. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42376. }
  42377. else {
  42378. defines["UV1"] = false;
  42379. defines["UV2"] = false;
  42380. }
  42381. if (useVertexColor) {
  42382. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42383. defines["VERTEXCOLOR"] = hasVertexColors;
  42384. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42385. }
  42386. if (useBones) {
  42387. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42388. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42389. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42390. }
  42391. else {
  42392. defines["NUM_BONE_INFLUENCERS"] = 0;
  42393. defines["BonesPerMesh"] = 0;
  42394. }
  42395. }
  42396. if (useMorphTargets) {
  42397. var manager = mesh.morphTargetManager;
  42398. if (manager) {
  42399. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42400. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42401. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42402. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42403. }
  42404. else {
  42405. defines["MORPHTARGETS_TANGENT"] = false;
  42406. defines["MORPHTARGETS_NORMAL"] = false;
  42407. defines["MORPHTARGETS"] = false;
  42408. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42409. }
  42410. }
  42411. return true;
  42412. };
  42413. /**
  42414. * Prepares the defines related to the light information passed in parameter
  42415. * @param scene The scene we are intending to draw
  42416. * @param mesh The mesh the effect is compiling for
  42417. * @param defines The defines to update
  42418. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42419. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42420. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42421. * @returns true if normals will be required for the rest of the effect
  42422. */
  42423. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42424. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42425. if (disableLighting === void 0) { disableLighting = false; }
  42426. if (!defines._areLightsDirty) {
  42427. return defines._needNormals;
  42428. }
  42429. var lightIndex = 0;
  42430. var needNormals = false;
  42431. var needRebuild = false;
  42432. var lightmapMode = false;
  42433. var shadowEnabled = false;
  42434. var specularEnabled = false;
  42435. if (scene.lightsEnabled && !disableLighting) {
  42436. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42437. var light = _a[_i];
  42438. needNormals = true;
  42439. if (defines["LIGHT" + lightIndex] === undefined) {
  42440. needRebuild = true;
  42441. }
  42442. defines["LIGHT" + lightIndex] = true;
  42443. defines["SPOTLIGHT" + lightIndex] = false;
  42444. defines["HEMILIGHT" + lightIndex] = false;
  42445. defines["POINTLIGHT" + lightIndex] = false;
  42446. defines["DIRLIGHT" + lightIndex] = false;
  42447. var type;
  42448. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42449. type = "SPOTLIGHT" + lightIndex;
  42450. var spotLight = light;
  42451. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42452. }
  42453. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42454. type = "HEMILIGHT" + lightIndex;
  42455. }
  42456. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42457. type = "POINTLIGHT" + lightIndex;
  42458. }
  42459. else {
  42460. type = "DIRLIGHT" + lightIndex;
  42461. }
  42462. defines[type] = true;
  42463. // Specular
  42464. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42465. specularEnabled = true;
  42466. }
  42467. // Shadows
  42468. defines["SHADOW" + lightIndex] = false;
  42469. defines["SHADOWPCF" + lightIndex] = false;
  42470. defines["SHADOWPCSS" + lightIndex] = false;
  42471. defines["SHADOWPOISSON" + lightIndex] = false;
  42472. defines["SHADOWESM" + lightIndex] = false;
  42473. defines["SHADOWCUBE" + lightIndex] = false;
  42474. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42475. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42476. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42477. var shadowGenerator = light.getShadowGenerator();
  42478. if (shadowGenerator) {
  42479. shadowEnabled = true;
  42480. shadowGenerator.prepareDefines(defines, lightIndex);
  42481. }
  42482. }
  42483. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42484. lightmapMode = true;
  42485. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42486. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42487. }
  42488. else {
  42489. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42490. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42491. }
  42492. lightIndex++;
  42493. if (lightIndex === maxSimultaneousLights)
  42494. break;
  42495. }
  42496. }
  42497. defines["SPECULARTERM"] = specularEnabled;
  42498. defines["SHADOWS"] = shadowEnabled;
  42499. // Resetting all other lights if any
  42500. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42501. if (defines["LIGHT" + index] !== undefined) {
  42502. defines["LIGHT" + index] = false;
  42503. defines["HEMILIGHT" + lightIndex] = false;
  42504. defines["POINTLIGHT" + lightIndex] = false;
  42505. defines["DIRLIGHT" + lightIndex] = false;
  42506. defines["SPOTLIGHT" + lightIndex] = false;
  42507. defines["SHADOW" + lightIndex] = false;
  42508. }
  42509. }
  42510. var caps = scene.getEngine().getCaps();
  42511. if (defines["SHADOWFLOAT"] === undefined) {
  42512. needRebuild = true;
  42513. }
  42514. defines["SHADOWFLOAT"] = shadowEnabled &&
  42515. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42516. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42517. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42518. if (needRebuild) {
  42519. defines.rebuild();
  42520. }
  42521. return needNormals;
  42522. };
  42523. /**
  42524. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42525. * that won t be acctive due to defines being turned off.
  42526. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42527. * @param samplersList The samplers list
  42528. * @param defines The defines helping in the list generation
  42529. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42530. */
  42531. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42532. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42533. var uniformsList;
  42534. var uniformBuffersList = null;
  42535. if (uniformsListOrOptions.uniformsNames) {
  42536. var options = uniformsListOrOptions;
  42537. uniformsList = options.uniformsNames;
  42538. uniformBuffersList = options.uniformBuffersNames;
  42539. samplersList = options.samplers;
  42540. defines = options.defines;
  42541. maxSimultaneousLights = options.maxSimultaneousLights;
  42542. }
  42543. else {
  42544. uniformsList = uniformsListOrOptions;
  42545. if (!samplersList) {
  42546. samplersList = [];
  42547. }
  42548. }
  42549. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42550. if (!defines["LIGHT" + lightIndex]) {
  42551. break;
  42552. }
  42553. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42554. if (uniformBuffersList) {
  42555. uniformBuffersList.push("Light" + lightIndex);
  42556. }
  42557. samplersList.push("shadowSampler" + lightIndex);
  42558. samplersList.push("depthSampler" + lightIndex);
  42559. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42560. samplersList.push("projectionLightSampler" + lightIndex);
  42561. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42562. }
  42563. }
  42564. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42565. uniformsList.push("morphTargetInfluences");
  42566. }
  42567. };
  42568. /**
  42569. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42570. * @param defines The defines to update while falling back
  42571. * @param fallbacks The authorized effect fallbacks
  42572. * @param maxSimultaneousLights The maximum number of lights allowed
  42573. * @param rank the current rank of the Effect
  42574. * @returns The newly affected rank
  42575. */
  42576. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42577. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42578. if (rank === void 0) { rank = 0; }
  42579. var lightFallbackRank = 0;
  42580. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42581. if (!defines["LIGHT" + lightIndex]) {
  42582. break;
  42583. }
  42584. if (lightIndex > 0) {
  42585. lightFallbackRank = rank + lightIndex;
  42586. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42587. }
  42588. if (!defines["SHADOWS"]) {
  42589. if (defines["SHADOW" + lightIndex]) {
  42590. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42591. }
  42592. if (defines["SHADOWPCF" + lightIndex]) {
  42593. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42594. }
  42595. if (defines["SHADOWPCSS" + lightIndex]) {
  42596. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42597. }
  42598. if (defines["SHADOWPOISSON" + lightIndex]) {
  42599. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42600. }
  42601. if (defines["SHADOWESM" + lightIndex]) {
  42602. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42603. }
  42604. }
  42605. }
  42606. return lightFallbackRank++;
  42607. };
  42608. /**
  42609. * Prepares the list of attributes required for morph targets according to the effect defines.
  42610. * @param attribs The current list of supported attribs
  42611. * @param mesh The mesh to prepare the morph targets attributes for
  42612. * @param defines The current Defines of the effect
  42613. */
  42614. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42615. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42616. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42617. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42618. var manager = mesh.morphTargetManager;
  42619. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42620. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42621. for (var index = 0; index < influencers; index++) {
  42622. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42623. if (normal) {
  42624. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42625. }
  42626. if (tangent) {
  42627. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42628. }
  42629. if (attribs.length > maxAttributesCount) {
  42630. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42631. }
  42632. }
  42633. }
  42634. };
  42635. /**
  42636. * Prepares the list of attributes required for bones according to the effect defines.
  42637. * @param attribs The current list of supported attribs
  42638. * @param mesh The mesh to prepare the bones attributes for
  42639. * @param defines The current Defines of the effect
  42640. * @param fallbacks The current efffect fallback strategy
  42641. */
  42642. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42643. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42644. fallbacks.addCPUSkinningFallback(0, mesh);
  42645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42647. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42650. }
  42651. }
  42652. };
  42653. /**
  42654. * Prepares the list of attributes required for instances according to the effect defines.
  42655. * @param attribs The current list of supported attribs
  42656. * @param defines The current Defines of the effect
  42657. */
  42658. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42659. if (defines["INSTANCES"]) {
  42660. attribs.push("world0");
  42661. attribs.push("world1");
  42662. attribs.push("world2");
  42663. attribs.push("world3");
  42664. }
  42665. };
  42666. /**
  42667. * Binds the light shadow information to the effect for the given mesh.
  42668. * @param light The light containing the generator
  42669. * @param scene The scene the lights belongs to
  42670. * @param mesh The mesh we are binding the information to render
  42671. * @param lightIndex The light index in the effect used to render the mesh
  42672. * @param effect The effect we are binding the data to
  42673. */
  42674. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42675. if (light.shadowEnabled && mesh.receiveShadows) {
  42676. var shadowGenerator = light.getShadowGenerator();
  42677. if (shadowGenerator) {
  42678. shadowGenerator.bindShadowLight(lightIndex, effect);
  42679. }
  42680. }
  42681. };
  42682. /**
  42683. * Binds the light information to the effect.
  42684. * @param light The light containing the generator
  42685. * @param effect The effect we are binding the data to
  42686. * @param lightIndex The light index in the effect used to render
  42687. */
  42688. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42689. light.transferToEffect(effect, lightIndex + "");
  42690. };
  42691. /**
  42692. * Binds the lights information from the scene to the effect for the given mesh.
  42693. * @param scene The scene the lights belongs to
  42694. * @param mesh The mesh we are binding the information to render
  42695. * @param effect The effect we are binding the data to
  42696. * @param defines The generated defines for the effect
  42697. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42698. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42699. */
  42700. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42701. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42702. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42703. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42704. for (var i = 0; i < len; i++) {
  42705. var light = mesh._lightSources[i];
  42706. var iAsString = i.toString();
  42707. var scaledIntensity = light.getScaledIntensity();
  42708. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42709. MaterialHelper.BindLightProperties(light, effect, i);
  42710. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42711. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42712. if (defines["SPECULARTERM"]) {
  42713. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42714. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42715. }
  42716. // Shadows
  42717. if (scene.shadowsEnabled) {
  42718. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42719. }
  42720. light._uniformBuffer.update();
  42721. }
  42722. };
  42723. /**
  42724. * Binds the fog information from the scene to the effect for the given mesh.
  42725. * @param scene The scene the lights belongs to
  42726. * @param mesh The mesh we are binding the information to render
  42727. * @param effect The effect we are binding the data to
  42728. */
  42729. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42730. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42731. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42732. effect.setColor3("vFogColor", scene.fogColor);
  42733. }
  42734. };
  42735. /**
  42736. * Binds the bones information from the mesh to the effect.
  42737. * @param mesh The mesh we are binding the information to render
  42738. * @param effect The effect we are binding the data to
  42739. */
  42740. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42741. if (!effect || !mesh) {
  42742. return;
  42743. }
  42744. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42745. mesh.computeBonesUsingShaders = false;
  42746. }
  42747. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42748. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42749. if (matrices) {
  42750. effect.setMatrices("mBones", matrices);
  42751. }
  42752. }
  42753. };
  42754. /**
  42755. * Binds the morph targets information from the mesh to the effect.
  42756. * @param abstractMesh The mesh we are binding the information to render
  42757. * @param effect The effect we are binding the data to
  42758. */
  42759. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42760. var manager = abstractMesh.morphTargetManager;
  42761. if (!abstractMesh || !manager) {
  42762. return;
  42763. }
  42764. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42765. };
  42766. /**
  42767. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42768. * @param defines The generated defines used in the effect
  42769. * @param effect The effect we are binding the data to
  42770. * @param scene The scene we are willing to render with logarithmic scale for
  42771. */
  42772. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42773. if (defines["LOGARITHMICDEPTH"]) {
  42774. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42775. }
  42776. };
  42777. /**
  42778. * Binds the clip plane information from the scene to the effect.
  42779. * @param scene The scene the clip plane information are extracted from
  42780. * @param effect The effect we are binding the data to
  42781. */
  42782. MaterialHelper.BindClipPlane = function (effect, scene) {
  42783. if (scene.clipPlane) {
  42784. var clipPlane = scene.clipPlane;
  42785. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42786. }
  42787. };
  42788. return MaterialHelper;
  42789. }());
  42790. BABYLON.MaterialHelper = MaterialHelper;
  42791. })(BABYLON || (BABYLON = {}));
  42792. //# sourceMappingURL=babylon.materialHelper.js.map
  42793. var BABYLON;
  42794. (function (BABYLON) {
  42795. var PushMaterial = /** @class */ (function (_super) {
  42796. __extends(PushMaterial, _super);
  42797. function PushMaterial(name, scene) {
  42798. var _this = _super.call(this, name, scene) || this;
  42799. _this._normalMatrix = new BABYLON.Matrix();
  42800. _this.storeEffectOnSubMeshes = true;
  42801. return _this;
  42802. }
  42803. PushMaterial.prototype.getEffect = function () {
  42804. return this._activeEffect;
  42805. };
  42806. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42807. if (!mesh) {
  42808. return false;
  42809. }
  42810. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42811. return true;
  42812. }
  42813. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42814. };
  42815. /**
  42816. * Binds the given world matrix to the active effect
  42817. *
  42818. * @param world the matrix to bind
  42819. */
  42820. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42821. this._activeEffect.setMatrix("world", world);
  42822. };
  42823. /**
  42824. * Binds the given normal matrix to the active effect
  42825. *
  42826. * @param normalMatrix the matrix to bind
  42827. */
  42828. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42829. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42830. };
  42831. PushMaterial.prototype.bind = function (world, mesh) {
  42832. if (!mesh) {
  42833. return;
  42834. }
  42835. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42836. };
  42837. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42838. if (effect === void 0) { effect = null; }
  42839. _super.prototype._afterBind.call(this, mesh);
  42840. this.getScene()._cachedEffect = effect;
  42841. };
  42842. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42843. if (visibility === void 0) { visibility = 1; }
  42844. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42845. };
  42846. return PushMaterial;
  42847. }(BABYLON.Material));
  42848. BABYLON.PushMaterial = PushMaterial;
  42849. })(BABYLON || (BABYLON = {}));
  42850. //# sourceMappingURL=babylon.pushMaterial.js.map
  42851. var BABYLON;
  42852. (function (BABYLON) {
  42853. /** @hidden */
  42854. var StandardMaterialDefines = /** @class */ (function (_super) {
  42855. __extends(StandardMaterialDefines, _super);
  42856. function StandardMaterialDefines() {
  42857. var _this = _super.call(this) || this;
  42858. _this.MAINUV1 = false;
  42859. _this.MAINUV2 = false;
  42860. _this.DIFFUSE = false;
  42861. _this.DIFFUSEDIRECTUV = 0;
  42862. _this.AMBIENT = false;
  42863. _this.AMBIENTDIRECTUV = 0;
  42864. _this.OPACITY = false;
  42865. _this.OPACITYDIRECTUV = 0;
  42866. _this.OPACITYRGB = false;
  42867. _this.REFLECTION = false;
  42868. _this.EMISSIVE = false;
  42869. _this.EMISSIVEDIRECTUV = 0;
  42870. _this.SPECULAR = false;
  42871. _this.SPECULARDIRECTUV = 0;
  42872. _this.BUMP = false;
  42873. _this.BUMPDIRECTUV = 0;
  42874. _this.PARALLAX = false;
  42875. _this.PARALLAXOCCLUSION = false;
  42876. _this.SPECULAROVERALPHA = false;
  42877. _this.CLIPPLANE = false;
  42878. _this.ALPHATEST = false;
  42879. _this.DEPTHPREPASS = false;
  42880. _this.ALPHAFROMDIFFUSE = false;
  42881. _this.POINTSIZE = false;
  42882. _this.FOG = false;
  42883. _this.SPECULARTERM = false;
  42884. _this.DIFFUSEFRESNEL = false;
  42885. _this.OPACITYFRESNEL = false;
  42886. _this.REFLECTIONFRESNEL = false;
  42887. _this.REFRACTIONFRESNEL = false;
  42888. _this.EMISSIVEFRESNEL = false;
  42889. _this.FRESNEL = false;
  42890. _this.NORMAL = false;
  42891. _this.UV1 = false;
  42892. _this.UV2 = false;
  42893. _this.VERTEXCOLOR = false;
  42894. _this.VERTEXALPHA = false;
  42895. _this.NUM_BONE_INFLUENCERS = 0;
  42896. _this.BonesPerMesh = 0;
  42897. _this.INSTANCES = false;
  42898. _this.GLOSSINESS = false;
  42899. _this.ROUGHNESS = false;
  42900. _this.EMISSIVEASILLUMINATION = false;
  42901. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42902. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42903. _this.LIGHTMAP = false;
  42904. _this.LIGHTMAPDIRECTUV = 0;
  42905. _this.OBJECTSPACE_NORMALMAP = false;
  42906. _this.USELIGHTMAPASSHADOWMAP = false;
  42907. _this.REFLECTIONMAP_3D = false;
  42908. _this.REFLECTIONMAP_SPHERICAL = false;
  42909. _this.REFLECTIONMAP_PLANAR = false;
  42910. _this.REFLECTIONMAP_CUBIC = false;
  42911. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42912. _this.REFLECTIONMAP_PROJECTION = false;
  42913. _this.REFLECTIONMAP_SKYBOX = false;
  42914. _this.REFLECTIONMAP_EXPLICIT = false;
  42915. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42916. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42917. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42918. _this.INVERTCUBICMAP = false;
  42919. _this.LOGARITHMICDEPTH = false;
  42920. _this.REFRACTION = false;
  42921. _this.REFRACTIONMAP_3D = false;
  42922. _this.REFLECTIONOVERALPHA = false;
  42923. _this.TWOSIDEDLIGHTING = false;
  42924. _this.SHADOWFLOAT = false;
  42925. _this.MORPHTARGETS = false;
  42926. _this.MORPHTARGETS_NORMAL = false;
  42927. _this.MORPHTARGETS_TANGENT = false;
  42928. _this.NUM_MORPH_INFLUENCERS = 0;
  42929. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42930. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42931. _this.IMAGEPROCESSING = false;
  42932. _this.VIGNETTE = false;
  42933. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42934. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42935. _this.TONEMAPPING = false;
  42936. _this.CONTRAST = false;
  42937. _this.COLORCURVES = false;
  42938. _this.COLORGRADING = false;
  42939. _this.COLORGRADING3D = false;
  42940. _this.SAMPLER3DGREENDEPTH = false;
  42941. _this.SAMPLER3DBGRMAP = false;
  42942. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42943. /**
  42944. * If the reflection texture on this material is in linear color space
  42945. * @hidden
  42946. */
  42947. _this.IS_REFLECTION_LINEAR = false;
  42948. /**
  42949. * If the refraction texture on this material is in linear color space
  42950. * @hidden
  42951. */
  42952. _this.IS_REFRACTION_LINEAR = false;
  42953. _this.EXPOSURE = false;
  42954. _this.rebuild();
  42955. return _this;
  42956. }
  42957. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42958. var modes = [
  42959. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42960. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42961. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42962. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42963. ];
  42964. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42965. var mode = modes_1[_i];
  42966. this[mode] = (mode === modeToEnable);
  42967. }
  42968. };
  42969. return StandardMaterialDefines;
  42970. }(BABYLON.MaterialDefines));
  42971. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42972. var StandardMaterial = /** @class */ (function (_super) {
  42973. __extends(StandardMaterial, _super);
  42974. function StandardMaterial(name, scene) {
  42975. var _this = _super.call(this, name, scene) || this;
  42976. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42977. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42978. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42979. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42980. _this.specularPower = 64;
  42981. _this._useAlphaFromDiffuseTexture = false;
  42982. _this._useEmissiveAsIllumination = false;
  42983. _this._linkEmissiveWithDiffuse = false;
  42984. _this._useSpecularOverAlpha = false;
  42985. _this._useReflectionOverAlpha = false;
  42986. _this._disableLighting = false;
  42987. _this._useObjectSpaceNormalMap = false;
  42988. _this._useParallax = false;
  42989. _this._useParallaxOcclusion = false;
  42990. _this.parallaxScaleBias = 0.05;
  42991. _this._roughness = 0;
  42992. _this.indexOfRefraction = 0.98;
  42993. _this.invertRefractionY = true;
  42994. /**
  42995. * Defines the alpha limits in alpha test mode
  42996. */
  42997. _this.alphaCutOff = 0.4;
  42998. _this._useLightmapAsShadowmap = false;
  42999. _this._useReflectionFresnelFromSpecular = false;
  43000. _this._useGlossinessFromSpecularMapAlpha = false;
  43001. _this._maxSimultaneousLights = 4;
  43002. /**
  43003. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43004. */
  43005. _this._invertNormalMapX = false;
  43006. /**
  43007. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43008. */
  43009. _this._invertNormalMapY = false;
  43010. /**
  43011. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43012. */
  43013. _this._twoSidedLighting = false;
  43014. _this._renderTargets = new BABYLON.SmartArray(16);
  43015. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43016. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43017. // Setup the default processing configuration to the scene.
  43018. _this._attachImageProcessingConfiguration(null);
  43019. _this.getRenderTargetTextures = function () {
  43020. _this._renderTargets.reset();
  43021. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43022. _this._renderTargets.push(_this._reflectionTexture);
  43023. }
  43024. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43025. _this._renderTargets.push(_this._refractionTexture);
  43026. }
  43027. return _this._renderTargets;
  43028. };
  43029. return _this;
  43030. }
  43031. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43032. /**
  43033. * Gets the image processing configuration used either in this material.
  43034. */
  43035. get: function () {
  43036. return this._imageProcessingConfiguration;
  43037. },
  43038. /**
  43039. * Sets the Default image processing configuration used either in the this material.
  43040. *
  43041. * If sets to null, the scene one is in use.
  43042. */
  43043. set: function (value) {
  43044. this._attachImageProcessingConfiguration(value);
  43045. // Ensure the effect will be rebuilt.
  43046. this._markAllSubMeshesAsTexturesDirty();
  43047. },
  43048. enumerable: true,
  43049. configurable: true
  43050. });
  43051. /**
  43052. * Attaches a new image processing configuration to the Standard Material.
  43053. * @param configuration
  43054. */
  43055. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43056. var _this = this;
  43057. if (configuration === this._imageProcessingConfiguration) {
  43058. return;
  43059. }
  43060. // Detaches observer.
  43061. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43062. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43063. }
  43064. // Pick the scene configuration if needed.
  43065. if (!configuration) {
  43066. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43067. }
  43068. else {
  43069. this._imageProcessingConfiguration = configuration;
  43070. }
  43071. // Attaches observer.
  43072. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43073. _this._markAllSubMeshesAsImageProcessingDirty();
  43074. });
  43075. };
  43076. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43077. /**
  43078. * Gets wether the color curves effect is enabled.
  43079. */
  43080. get: function () {
  43081. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43082. },
  43083. /**
  43084. * Sets wether the color curves effect is enabled.
  43085. */
  43086. set: function (value) {
  43087. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43093. /**
  43094. * Gets wether the color grading effect is enabled.
  43095. */
  43096. get: function () {
  43097. return this.imageProcessingConfiguration.colorGradingEnabled;
  43098. },
  43099. /**
  43100. * Gets wether the color grading effect is enabled.
  43101. */
  43102. set: function (value) {
  43103. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43104. },
  43105. enumerable: true,
  43106. configurable: true
  43107. });
  43108. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43109. /**
  43110. * Gets wether tonemapping is enabled or not.
  43111. */
  43112. get: function () {
  43113. return this._imageProcessingConfiguration.toneMappingEnabled;
  43114. },
  43115. /**
  43116. * Sets wether tonemapping is enabled or not
  43117. */
  43118. set: function (value) {
  43119. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43120. },
  43121. enumerable: true,
  43122. configurable: true
  43123. });
  43124. ;
  43125. ;
  43126. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43127. /**
  43128. * The camera exposure used on this material.
  43129. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43130. * This corresponds to a photographic exposure.
  43131. */
  43132. get: function () {
  43133. return this._imageProcessingConfiguration.exposure;
  43134. },
  43135. /**
  43136. * The camera exposure used on this material.
  43137. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43138. * This corresponds to a photographic exposure.
  43139. */
  43140. set: function (value) {
  43141. this._imageProcessingConfiguration.exposure = value;
  43142. },
  43143. enumerable: true,
  43144. configurable: true
  43145. });
  43146. ;
  43147. ;
  43148. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43149. /**
  43150. * Gets The camera contrast used on this material.
  43151. */
  43152. get: function () {
  43153. return this._imageProcessingConfiguration.contrast;
  43154. },
  43155. /**
  43156. * Sets The camera contrast used on this material.
  43157. */
  43158. set: function (value) {
  43159. this._imageProcessingConfiguration.contrast = value;
  43160. },
  43161. enumerable: true,
  43162. configurable: true
  43163. });
  43164. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43165. /**
  43166. * Gets the Color Grading 2D Lookup Texture.
  43167. */
  43168. get: function () {
  43169. return this._imageProcessingConfiguration.colorGradingTexture;
  43170. },
  43171. /**
  43172. * Sets the Color Grading 2D Lookup Texture.
  43173. */
  43174. set: function (value) {
  43175. this._imageProcessingConfiguration.colorGradingTexture = value;
  43176. },
  43177. enumerable: true,
  43178. configurable: true
  43179. });
  43180. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43181. /**
  43182. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43183. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43184. * 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;
  43185. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43186. */
  43187. get: function () {
  43188. return this._imageProcessingConfiguration.colorCurves;
  43189. },
  43190. /**
  43191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43193. * 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;
  43194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43195. */
  43196. set: function (value) {
  43197. this._imageProcessingConfiguration.colorCurves = value;
  43198. },
  43199. enumerable: true,
  43200. configurable: true
  43201. });
  43202. StandardMaterial.prototype.getClassName = function () {
  43203. return "StandardMaterial";
  43204. };
  43205. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43206. get: function () {
  43207. return this._useLogarithmicDepth;
  43208. },
  43209. set: function (value) {
  43210. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43211. this._markAllSubMeshesAsMiscDirty();
  43212. },
  43213. enumerable: true,
  43214. configurable: true
  43215. });
  43216. StandardMaterial.prototype.needAlphaBlending = function () {
  43217. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43218. };
  43219. StandardMaterial.prototype.needAlphaTesting = function () {
  43220. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43221. };
  43222. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43223. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43224. };
  43225. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43226. return this._diffuseTexture;
  43227. };
  43228. /**
  43229. * Child classes can use it to update shaders
  43230. */
  43231. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43232. if (useInstances === void 0) { useInstances = false; }
  43233. if (subMesh.effect && this.isFrozen) {
  43234. if (this._wasPreviouslyReady && subMesh.effect) {
  43235. return true;
  43236. }
  43237. }
  43238. if (!subMesh._materialDefines) {
  43239. subMesh._materialDefines = new StandardMaterialDefines();
  43240. }
  43241. var scene = this.getScene();
  43242. var defines = subMesh._materialDefines;
  43243. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43244. if (defines._renderId === scene.getRenderId()) {
  43245. return true;
  43246. }
  43247. }
  43248. var engine = scene.getEngine();
  43249. // Lights
  43250. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43251. // Textures
  43252. if (defines._areTexturesDirty) {
  43253. defines._needUVs = false;
  43254. defines.MAINUV1 = false;
  43255. defines.MAINUV2 = false;
  43256. if (scene.texturesEnabled) {
  43257. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43258. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43259. return false;
  43260. }
  43261. else {
  43262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43263. }
  43264. }
  43265. else {
  43266. defines.DIFFUSE = false;
  43267. }
  43268. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43269. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43270. return false;
  43271. }
  43272. else {
  43273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43274. }
  43275. }
  43276. else {
  43277. defines.AMBIENT = false;
  43278. }
  43279. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43280. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43281. return false;
  43282. }
  43283. else {
  43284. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43285. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43286. }
  43287. }
  43288. else {
  43289. defines.OPACITY = false;
  43290. }
  43291. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43292. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43293. return false;
  43294. }
  43295. else {
  43296. defines._needNormals = true;
  43297. defines.REFLECTION = true;
  43298. defines.ROUGHNESS = (this._roughness > 0);
  43299. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43300. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43301. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43302. switch (this._reflectionTexture.coordinatesMode) {
  43303. case BABYLON.Texture.EXPLICIT_MODE:
  43304. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43305. break;
  43306. case BABYLON.Texture.PLANAR_MODE:
  43307. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43308. break;
  43309. case BABYLON.Texture.PROJECTION_MODE:
  43310. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43311. break;
  43312. case BABYLON.Texture.SKYBOX_MODE:
  43313. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43314. break;
  43315. case BABYLON.Texture.SPHERICAL_MODE:
  43316. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43317. break;
  43318. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43319. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43320. break;
  43321. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43322. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43323. break;
  43324. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43325. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43326. break;
  43327. case BABYLON.Texture.CUBIC_MODE:
  43328. case BABYLON.Texture.INVCUBIC_MODE:
  43329. default:
  43330. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43331. break;
  43332. }
  43333. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43334. }
  43335. }
  43336. else {
  43337. defines.REFLECTION = false;
  43338. }
  43339. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43340. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43341. return false;
  43342. }
  43343. else {
  43344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43345. }
  43346. }
  43347. else {
  43348. defines.EMISSIVE = false;
  43349. }
  43350. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43351. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43352. return false;
  43353. }
  43354. else {
  43355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43356. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43357. }
  43358. }
  43359. else {
  43360. defines.LIGHTMAP = false;
  43361. }
  43362. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43363. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43364. return false;
  43365. }
  43366. else {
  43367. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43368. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43369. }
  43370. }
  43371. else {
  43372. defines.SPECULAR = false;
  43373. }
  43374. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43375. // Bump texure can not be not blocking.
  43376. if (!this._bumpTexture.isReady()) {
  43377. return false;
  43378. }
  43379. else {
  43380. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43381. defines.PARALLAX = this._useParallax;
  43382. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43383. }
  43384. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43385. }
  43386. else {
  43387. defines.BUMP = false;
  43388. }
  43389. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43390. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43391. return false;
  43392. }
  43393. else {
  43394. defines._needUVs = true;
  43395. defines.REFRACTION = true;
  43396. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43397. }
  43398. }
  43399. else {
  43400. defines.REFRACTION = false;
  43401. }
  43402. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43403. }
  43404. else {
  43405. defines.DIFFUSE = false;
  43406. defines.AMBIENT = false;
  43407. defines.OPACITY = false;
  43408. defines.REFLECTION = false;
  43409. defines.EMISSIVE = false;
  43410. defines.LIGHTMAP = false;
  43411. defines.BUMP = false;
  43412. defines.REFRACTION = false;
  43413. }
  43414. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43415. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43416. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43417. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43418. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43419. }
  43420. if (defines._areImageProcessingDirty) {
  43421. if (!this._imageProcessingConfiguration.isReady()) {
  43422. return false;
  43423. }
  43424. this._imageProcessingConfiguration.prepareDefines(defines);
  43425. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43426. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43427. }
  43428. if (defines._areFresnelDirty) {
  43429. if (StandardMaterial.FresnelEnabled) {
  43430. // Fresnel
  43431. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43432. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43433. this._reflectionFresnelParameters) {
  43434. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43435. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43436. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43437. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43438. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43439. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43440. defines._needNormals = true;
  43441. defines.FRESNEL = true;
  43442. }
  43443. }
  43444. else {
  43445. defines.FRESNEL = false;
  43446. }
  43447. }
  43448. // Misc.
  43449. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43450. // Attribs
  43451. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43452. // Values that need to be evaluated on every frame
  43453. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43454. // Get correct effect
  43455. if (defines.isDirty) {
  43456. defines.markAsProcessed();
  43457. scene.resetCachedMaterial();
  43458. // Fallbacks
  43459. var fallbacks = new BABYLON.EffectFallbacks();
  43460. if (defines.REFLECTION) {
  43461. fallbacks.addFallback(0, "REFLECTION");
  43462. }
  43463. if (defines.SPECULAR) {
  43464. fallbacks.addFallback(0, "SPECULAR");
  43465. }
  43466. if (defines.BUMP) {
  43467. fallbacks.addFallback(0, "BUMP");
  43468. }
  43469. if (defines.PARALLAX) {
  43470. fallbacks.addFallback(1, "PARALLAX");
  43471. }
  43472. if (defines.PARALLAXOCCLUSION) {
  43473. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43474. }
  43475. if (defines.SPECULAROVERALPHA) {
  43476. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43477. }
  43478. if (defines.FOG) {
  43479. fallbacks.addFallback(1, "FOG");
  43480. }
  43481. if (defines.POINTSIZE) {
  43482. fallbacks.addFallback(0, "POINTSIZE");
  43483. }
  43484. if (defines.LOGARITHMICDEPTH) {
  43485. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43486. }
  43487. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43488. if (defines.SPECULARTERM) {
  43489. fallbacks.addFallback(0, "SPECULARTERM");
  43490. }
  43491. if (defines.DIFFUSEFRESNEL) {
  43492. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43493. }
  43494. if (defines.OPACITYFRESNEL) {
  43495. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43496. }
  43497. if (defines.REFLECTIONFRESNEL) {
  43498. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43499. }
  43500. if (defines.EMISSIVEFRESNEL) {
  43501. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43502. }
  43503. if (defines.FRESNEL) {
  43504. fallbacks.addFallback(4, "FRESNEL");
  43505. }
  43506. //Attributes
  43507. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43508. if (defines.NORMAL) {
  43509. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43510. }
  43511. if (defines.UV1) {
  43512. attribs.push(BABYLON.VertexBuffer.UVKind);
  43513. }
  43514. if (defines.UV2) {
  43515. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43516. }
  43517. if (defines.VERTEXCOLOR) {
  43518. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43519. }
  43520. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43521. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43522. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43523. var shaderName = "default";
  43524. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43525. "vFogInfos", "vFogColor", "pointSize",
  43526. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43527. "mBones",
  43528. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43529. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43530. "vReflectionPosition", "vReflectionSize",
  43531. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43532. ];
  43533. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43534. var uniformBuffers = ["Material", "Scene"];
  43535. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43536. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43537. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43538. uniformsNames: uniforms,
  43539. uniformBuffersNames: uniformBuffers,
  43540. samplers: samplers,
  43541. defines: defines,
  43542. maxSimultaneousLights: this._maxSimultaneousLights
  43543. });
  43544. if (this.customShaderNameResolve) {
  43545. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43546. }
  43547. var join = defines.toString();
  43548. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43549. attributes: attribs,
  43550. uniformsNames: uniforms,
  43551. uniformBuffersNames: uniformBuffers,
  43552. samplers: samplers,
  43553. defines: join,
  43554. fallbacks: fallbacks,
  43555. onCompiled: this.onCompiled,
  43556. onError: this.onError,
  43557. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43558. }, engine), defines);
  43559. this.buildUniformLayout();
  43560. }
  43561. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43562. return false;
  43563. }
  43564. defines._renderId = scene.getRenderId();
  43565. this._wasPreviouslyReady = true;
  43566. return true;
  43567. };
  43568. StandardMaterial.prototype.buildUniformLayout = function () {
  43569. // Order is important !
  43570. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43571. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43572. this._uniformBuffer.addUniform("opacityParts", 4);
  43573. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43574. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43575. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43576. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43577. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43578. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43579. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43580. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43581. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43582. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43583. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43584. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43585. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43586. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43587. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43588. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43589. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43590. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43591. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43592. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43593. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43594. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43595. this._uniformBuffer.addUniform("specularMatrix", 16);
  43596. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43597. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43598. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43599. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43600. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43601. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43602. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43603. this._uniformBuffer.addUniform("pointSize", 1);
  43604. this._uniformBuffer.create();
  43605. };
  43606. StandardMaterial.prototype.unbind = function () {
  43607. if (this._activeEffect) {
  43608. var needFlag = false;
  43609. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43610. this._activeEffect.setTexture("reflection2DSampler", null);
  43611. needFlag = true;
  43612. }
  43613. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43614. this._activeEffect.setTexture("refraction2DSampler", null);
  43615. needFlag = true;
  43616. }
  43617. if (needFlag) {
  43618. this._markAllSubMeshesAsTexturesDirty();
  43619. }
  43620. }
  43621. _super.prototype.unbind.call(this);
  43622. };
  43623. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43624. var scene = this.getScene();
  43625. var defines = subMesh._materialDefines;
  43626. if (!defines) {
  43627. return;
  43628. }
  43629. var effect = subMesh.effect;
  43630. if (!effect) {
  43631. return;
  43632. }
  43633. this._activeEffect = effect;
  43634. // Matrices
  43635. this.bindOnlyWorldMatrix(world);
  43636. // Normal Matrix
  43637. if (defines.OBJECTSPACE_NORMALMAP) {
  43638. world.toNormalMatrix(this._normalMatrix);
  43639. this.bindOnlyNormalMatrix(this._normalMatrix);
  43640. }
  43641. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43642. // Bones
  43643. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43644. if (mustRebind) {
  43645. this._uniformBuffer.bindToEffect(effect, "Material");
  43646. this.bindViewProjection(effect);
  43647. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43648. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43649. // Fresnel
  43650. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43651. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43652. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43653. }
  43654. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43655. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43656. }
  43657. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43658. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43659. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43660. }
  43661. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43662. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43663. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43664. }
  43665. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43666. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43667. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43668. }
  43669. }
  43670. // Textures
  43671. if (scene.texturesEnabled) {
  43672. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43673. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43674. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43675. if (this._diffuseTexture.hasAlpha) {
  43676. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43677. }
  43678. }
  43679. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43680. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43681. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43682. }
  43683. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43684. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43685. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43686. }
  43687. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43688. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43689. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43690. if (this._reflectionTexture.boundingBoxSize) {
  43691. var cubeTexture = this._reflectionTexture;
  43692. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43693. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43694. }
  43695. }
  43696. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43697. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43698. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43699. }
  43700. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43701. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43702. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43703. }
  43704. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43705. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43706. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43707. }
  43708. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43709. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43710. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43711. if (scene._mirroredCameraPosition) {
  43712. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43713. }
  43714. else {
  43715. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43716. }
  43717. }
  43718. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43719. var depth = 1.0;
  43720. if (!this._refractionTexture.isCube) {
  43721. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43722. if (this._refractionTexture.depth) {
  43723. depth = this._refractionTexture.depth;
  43724. }
  43725. }
  43726. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43727. }
  43728. }
  43729. // Point size
  43730. if (this.pointsCloud) {
  43731. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43732. }
  43733. if (defines.SPECULARTERM) {
  43734. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43735. }
  43736. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43737. // Diffuse
  43738. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43739. }
  43740. // Textures
  43741. if (scene.texturesEnabled) {
  43742. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43743. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43744. }
  43745. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43746. effect.setTexture("ambientSampler", this._ambientTexture);
  43747. }
  43748. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43749. effect.setTexture("opacitySampler", this._opacityTexture);
  43750. }
  43751. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43752. if (this._reflectionTexture.isCube) {
  43753. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43754. }
  43755. else {
  43756. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43757. }
  43758. }
  43759. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43760. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43761. }
  43762. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43763. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43764. }
  43765. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43766. effect.setTexture("specularSampler", this._specularTexture);
  43767. }
  43768. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43769. effect.setTexture("bumpSampler", this._bumpTexture);
  43770. }
  43771. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43772. var depth = 1.0;
  43773. if (this._refractionTexture.isCube) {
  43774. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43775. }
  43776. else {
  43777. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43778. }
  43779. }
  43780. }
  43781. // Clip plane
  43782. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43783. // Colors
  43784. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43785. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43786. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43787. }
  43788. if (mustRebind || !this.isFrozen) {
  43789. // Lights
  43790. if (scene.lightsEnabled && !this._disableLighting) {
  43791. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43792. }
  43793. // View
  43794. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43795. this.bindView(effect);
  43796. }
  43797. // Fog
  43798. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43799. // Morph targets
  43800. if (defines.NUM_MORPH_INFLUENCERS) {
  43801. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43802. }
  43803. // Log. depth
  43804. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43805. // image processing
  43806. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43807. this._imageProcessingConfiguration.bind(this._activeEffect);
  43808. }
  43809. }
  43810. this._uniformBuffer.update();
  43811. this._afterBind(mesh, this._activeEffect);
  43812. };
  43813. StandardMaterial.prototype.getAnimatables = function () {
  43814. var results = [];
  43815. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43816. results.push(this._diffuseTexture);
  43817. }
  43818. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43819. results.push(this._ambientTexture);
  43820. }
  43821. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43822. results.push(this._opacityTexture);
  43823. }
  43824. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43825. results.push(this._reflectionTexture);
  43826. }
  43827. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43828. results.push(this._emissiveTexture);
  43829. }
  43830. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43831. results.push(this._specularTexture);
  43832. }
  43833. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43834. results.push(this._bumpTexture);
  43835. }
  43836. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43837. results.push(this._lightmapTexture);
  43838. }
  43839. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43840. results.push(this._refractionTexture);
  43841. }
  43842. return results;
  43843. };
  43844. StandardMaterial.prototype.getActiveTextures = function () {
  43845. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43846. if (this._diffuseTexture) {
  43847. activeTextures.push(this._diffuseTexture);
  43848. }
  43849. if (this._ambientTexture) {
  43850. activeTextures.push(this._ambientTexture);
  43851. }
  43852. if (this._opacityTexture) {
  43853. activeTextures.push(this._opacityTexture);
  43854. }
  43855. if (this._reflectionTexture) {
  43856. activeTextures.push(this._reflectionTexture);
  43857. }
  43858. if (this._emissiveTexture) {
  43859. activeTextures.push(this._emissiveTexture);
  43860. }
  43861. if (this._specularTexture) {
  43862. activeTextures.push(this._specularTexture);
  43863. }
  43864. if (this._bumpTexture) {
  43865. activeTextures.push(this._bumpTexture);
  43866. }
  43867. if (this._lightmapTexture) {
  43868. activeTextures.push(this._lightmapTexture);
  43869. }
  43870. if (this._refractionTexture) {
  43871. activeTextures.push(this._refractionTexture);
  43872. }
  43873. return activeTextures;
  43874. };
  43875. StandardMaterial.prototype.hasTexture = function (texture) {
  43876. if (_super.prototype.hasTexture.call(this, texture)) {
  43877. return true;
  43878. }
  43879. if (this._diffuseTexture === texture) {
  43880. return true;
  43881. }
  43882. if (this._ambientTexture === texture) {
  43883. return true;
  43884. }
  43885. if (this._opacityTexture === texture) {
  43886. return true;
  43887. }
  43888. if (this._reflectionTexture === texture) {
  43889. return true;
  43890. }
  43891. if (this._emissiveTexture === texture) {
  43892. return true;
  43893. }
  43894. if (this._specularTexture === texture) {
  43895. return true;
  43896. }
  43897. if (this._bumpTexture === texture) {
  43898. return true;
  43899. }
  43900. if (this._lightmapTexture === texture) {
  43901. return true;
  43902. }
  43903. if (this._refractionTexture === texture) {
  43904. return true;
  43905. }
  43906. return false;
  43907. };
  43908. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43909. if (forceDisposeTextures) {
  43910. if (this._diffuseTexture) {
  43911. this._diffuseTexture.dispose();
  43912. }
  43913. if (this._ambientTexture) {
  43914. this._ambientTexture.dispose();
  43915. }
  43916. if (this._opacityTexture) {
  43917. this._opacityTexture.dispose();
  43918. }
  43919. if (this._reflectionTexture) {
  43920. this._reflectionTexture.dispose();
  43921. }
  43922. if (this._emissiveTexture) {
  43923. this._emissiveTexture.dispose();
  43924. }
  43925. if (this._specularTexture) {
  43926. this._specularTexture.dispose();
  43927. }
  43928. if (this._bumpTexture) {
  43929. this._bumpTexture.dispose();
  43930. }
  43931. if (this._lightmapTexture) {
  43932. this._lightmapTexture.dispose();
  43933. }
  43934. if (this._refractionTexture) {
  43935. this._refractionTexture.dispose();
  43936. }
  43937. }
  43938. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43939. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43940. }
  43941. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43942. };
  43943. StandardMaterial.prototype.clone = function (name) {
  43944. var _this = this;
  43945. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43946. result.name = name;
  43947. result.id = name;
  43948. return result;
  43949. };
  43950. StandardMaterial.prototype.serialize = function () {
  43951. return BABYLON.SerializationHelper.Serialize(this);
  43952. };
  43953. // Statics
  43954. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43955. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43956. };
  43957. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43958. get: function () {
  43959. return StandardMaterial._DiffuseTextureEnabled;
  43960. },
  43961. set: function (value) {
  43962. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43963. return;
  43964. }
  43965. StandardMaterial._DiffuseTextureEnabled = value;
  43966. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43967. },
  43968. enumerable: true,
  43969. configurable: true
  43970. });
  43971. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43972. get: function () {
  43973. return StandardMaterial._AmbientTextureEnabled;
  43974. },
  43975. set: function (value) {
  43976. if (StandardMaterial._AmbientTextureEnabled === value) {
  43977. return;
  43978. }
  43979. StandardMaterial._AmbientTextureEnabled = value;
  43980. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43981. },
  43982. enumerable: true,
  43983. configurable: true
  43984. });
  43985. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43986. get: function () {
  43987. return StandardMaterial._OpacityTextureEnabled;
  43988. },
  43989. set: function (value) {
  43990. if (StandardMaterial._OpacityTextureEnabled === value) {
  43991. return;
  43992. }
  43993. StandardMaterial._OpacityTextureEnabled = value;
  43994. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43995. },
  43996. enumerable: true,
  43997. configurable: true
  43998. });
  43999. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44000. get: function () {
  44001. return StandardMaterial._ReflectionTextureEnabled;
  44002. },
  44003. set: function (value) {
  44004. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44005. return;
  44006. }
  44007. StandardMaterial._ReflectionTextureEnabled = value;
  44008. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44009. },
  44010. enumerable: true,
  44011. configurable: true
  44012. });
  44013. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44014. get: function () {
  44015. return StandardMaterial._EmissiveTextureEnabled;
  44016. },
  44017. set: function (value) {
  44018. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44019. return;
  44020. }
  44021. StandardMaterial._EmissiveTextureEnabled = value;
  44022. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44023. },
  44024. enumerable: true,
  44025. configurable: true
  44026. });
  44027. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44028. get: function () {
  44029. return StandardMaterial._SpecularTextureEnabled;
  44030. },
  44031. set: function (value) {
  44032. if (StandardMaterial._SpecularTextureEnabled === value) {
  44033. return;
  44034. }
  44035. StandardMaterial._SpecularTextureEnabled = value;
  44036. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44037. },
  44038. enumerable: true,
  44039. configurable: true
  44040. });
  44041. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44042. get: function () {
  44043. return StandardMaterial._BumpTextureEnabled;
  44044. },
  44045. set: function (value) {
  44046. if (StandardMaterial._BumpTextureEnabled === value) {
  44047. return;
  44048. }
  44049. StandardMaterial._BumpTextureEnabled = value;
  44050. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44051. },
  44052. enumerable: true,
  44053. configurable: true
  44054. });
  44055. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44056. get: function () {
  44057. return StandardMaterial._LightmapTextureEnabled;
  44058. },
  44059. set: function (value) {
  44060. if (StandardMaterial._LightmapTextureEnabled === value) {
  44061. return;
  44062. }
  44063. StandardMaterial._LightmapTextureEnabled = value;
  44064. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44065. },
  44066. enumerable: true,
  44067. configurable: true
  44068. });
  44069. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44070. get: function () {
  44071. return StandardMaterial._RefractionTextureEnabled;
  44072. },
  44073. set: function (value) {
  44074. if (StandardMaterial._RefractionTextureEnabled === value) {
  44075. return;
  44076. }
  44077. StandardMaterial._RefractionTextureEnabled = value;
  44078. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44079. },
  44080. enumerable: true,
  44081. configurable: true
  44082. });
  44083. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44084. get: function () {
  44085. return StandardMaterial._ColorGradingTextureEnabled;
  44086. },
  44087. set: function (value) {
  44088. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44089. return;
  44090. }
  44091. StandardMaterial._ColorGradingTextureEnabled = value;
  44092. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44093. },
  44094. enumerable: true,
  44095. configurable: true
  44096. });
  44097. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44098. get: function () {
  44099. return StandardMaterial._FresnelEnabled;
  44100. },
  44101. set: function (value) {
  44102. if (StandardMaterial._FresnelEnabled === value) {
  44103. return;
  44104. }
  44105. StandardMaterial._FresnelEnabled = value;
  44106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44107. },
  44108. enumerable: true,
  44109. configurable: true
  44110. });
  44111. // Flags used to enable or disable a type of texture for all Standard Materials
  44112. StandardMaterial._DiffuseTextureEnabled = true;
  44113. StandardMaterial._AmbientTextureEnabled = true;
  44114. StandardMaterial._OpacityTextureEnabled = true;
  44115. StandardMaterial._ReflectionTextureEnabled = true;
  44116. StandardMaterial._EmissiveTextureEnabled = true;
  44117. StandardMaterial._SpecularTextureEnabled = true;
  44118. StandardMaterial._BumpTextureEnabled = true;
  44119. StandardMaterial._LightmapTextureEnabled = true;
  44120. StandardMaterial._RefractionTextureEnabled = true;
  44121. StandardMaterial._ColorGradingTextureEnabled = true;
  44122. StandardMaterial._FresnelEnabled = true;
  44123. __decorate([
  44124. BABYLON.serializeAsTexture("diffuseTexture")
  44125. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44126. __decorate([
  44127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44128. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44129. __decorate([
  44130. BABYLON.serializeAsTexture("ambientTexture")
  44131. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44132. __decorate([
  44133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44134. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44135. __decorate([
  44136. BABYLON.serializeAsTexture("opacityTexture")
  44137. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44138. __decorate([
  44139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44140. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44141. __decorate([
  44142. BABYLON.serializeAsTexture("reflectionTexture")
  44143. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44144. __decorate([
  44145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44146. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44147. __decorate([
  44148. BABYLON.serializeAsTexture("emissiveTexture")
  44149. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44150. __decorate([
  44151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44152. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44153. __decorate([
  44154. BABYLON.serializeAsTexture("specularTexture")
  44155. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44156. __decorate([
  44157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44158. ], StandardMaterial.prototype, "specularTexture", void 0);
  44159. __decorate([
  44160. BABYLON.serializeAsTexture("bumpTexture")
  44161. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44162. __decorate([
  44163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44164. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44165. __decorate([
  44166. BABYLON.serializeAsTexture("lightmapTexture")
  44167. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44168. __decorate([
  44169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44170. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44171. __decorate([
  44172. BABYLON.serializeAsTexture("refractionTexture")
  44173. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44174. __decorate([
  44175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44176. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44177. __decorate([
  44178. BABYLON.serializeAsColor3("ambient")
  44179. ], StandardMaterial.prototype, "ambientColor", void 0);
  44180. __decorate([
  44181. BABYLON.serializeAsColor3("diffuse")
  44182. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44183. __decorate([
  44184. BABYLON.serializeAsColor3("specular")
  44185. ], StandardMaterial.prototype, "specularColor", void 0);
  44186. __decorate([
  44187. BABYLON.serializeAsColor3("emissive")
  44188. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44189. __decorate([
  44190. BABYLON.serialize()
  44191. ], StandardMaterial.prototype, "specularPower", void 0);
  44192. __decorate([
  44193. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44194. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44195. __decorate([
  44196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44197. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44198. __decorate([
  44199. BABYLON.serialize("useEmissiveAsIllumination")
  44200. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44201. __decorate([
  44202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44203. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44204. __decorate([
  44205. BABYLON.serialize("linkEmissiveWithDiffuse")
  44206. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44207. __decorate([
  44208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44209. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44210. __decorate([
  44211. BABYLON.serialize("useSpecularOverAlpha")
  44212. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44213. __decorate([
  44214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44215. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44216. __decorate([
  44217. BABYLON.serialize("useReflectionOverAlpha")
  44218. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44219. __decorate([
  44220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44221. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44222. __decorate([
  44223. BABYLON.serialize("disableLighting")
  44224. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44225. __decorate([
  44226. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44227. ], StandardMaterial.prototype, "disableLighting", void 0);
  44228. __decorate([
  44229. BABYLON.serialize("useObjectSpaceNormalMap")
  44230. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44231. __decorate([
  44232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44233. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44234. __decorate([
  44235. BABYLON.serialize("useParallax")
  44236. ], StandardMaterial.prototype, "_useParallax", void 0);
  44237. __decorate([
  44238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44239. ], StandardMaterial.prototype, "useParallax", void 0);
  44240. __decorate([
  44241. BABYLON.serialize("useParallaxOcclusion")
  44242. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44243. __decorate([
  44244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44245. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44246. __decorate([
  44247. BABYLON.serialize()
  44248. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44249. __decorate([
  44250. BABYLON.serialize("roughness")
  44251. ], StandardMaterial.prototype, "_roughness", void 0);
  44252. __decorate([
  44253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44254. ], StandardMaterial.prototype, "roughness", void 0);
  44255. __decorate([
  44256. BABYLON.serialize()
  44257. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44258. __decorate([
  44259. BABYLON.serialize()
  44260. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44261. __decorate([
  44262. BABYLON.serialize()
  44263. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44264. __decorate([
  44265. BABYLON.serialize("useLightmapAsShadowmap")
  44266. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44267. __decorate([
  44268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44269. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44270. __decorate([
  44271. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44272. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44273. __decorate([
  44274. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44275. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44276. __decorate([
  44277. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44278. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44279. __decorate([
  44280. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44281. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44282. __decorate([
  44283. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44284. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44285. __decorate([
  44286. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44287. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44288. __decorate([
  44289. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44290. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44291. __decorate([
  44292. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44293. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44294. __decorate([
  44295. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44296. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44297. __decorate([
  44298. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44299. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44300. __decorate([
  44301. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44302. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44303. __decorate([
  44304. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44305. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44306. __decorate([
  44307. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44308. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44309. __decorate([
  44310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44311. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44312. __decorate([
  44313. BABYLON.serialize("maxSimultaneousLights")
  44314. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44315. __decorate([
  44316. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44317. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44318. __decorate([
  44319. BABYLON.serialize("invertNormalMapX")
  44320. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44321. __decorate([
  44322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44323. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44324. __decorate([
  44325. BABYLON.serialize("invertNormalMapY")
  44326. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44327. __decorate([
  44328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44329. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44330. __decorate([
  44331. BABYLON.serialize("twoSidedLighting")
  44332. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44333. __decorate([
  44334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44335. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44336. __decorate([
  44337. BABYLON.serialize()
  44338. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44339. return StandardMaterial;
  44340. }(BABYLON.PushMaterial));
  44341. BABYLON.StandardMaterial = StandardMaterial;
  44342. })(BABYLON || (BABYLON = {}));
  44343. //# sourceMappingURL=babylon.standardMaterial.js.map
  44344. var BABYLON;
  44345. (function (BABYLON) {
  44346. /**
  44347. * Manages the defines for the PBR Material.
  44348. * @hiddenChildren
  44349. */
  44350. var PBRMaterialDefines = /** @class */ (function (_super) {
  44351. __extends(PBRMaterialDefines, _super);
  44352. /**
  44353. * Initializes the PBR Material defines.
  44354. */
  44355. function PBRMaterialDefines() {
  44356. var _this = _super.call(this) || this;
  44357. _this.PBR = true;
  44358. _this.MAINUV1 = false;
  44359. _this.MAINUV2 = false;
  44360. _this.UV1 = false;
  44361. _this.UV2 = false;
  44362. _this.ALBEDO = false;
  44363. _this.ALBEDODIRECTUV = 0;
  44364. _this.VERTEXCOLOR = false;
  44365. _this.AMBIENT = false;
  44366. _this.AMBIENTDIRECTUV = 0;
  44367. _this.AMBIENTINGRAYSCALE = false;
  44368. _this.OPACITY = false;
  44369. _this.VERTEXALPHA = false;
  44370. _this.OPACITYDIRECTUV = 0;
  44371. _this.OPACITYRGB = false;
  44372. _this.ALPHATEST = false;
  44373. _this.DEPTHPREPASS = false;
  44374. _this.ALPHABLEND = false;
  44375. _this.ALPHAFROMALBEDO = false;
  44376. _this.ALPHATESTVALUE = "0.5";
  44377. _this.SPECULAROVERALPHA = false;
  44378. _this.RADIANCEOVERALPHA = false;
  44379. _this.ALPHAFRESNEL = false;
  44380. _this.LINEARALPHAFRESNEL = false;
  44381. _this.PREMULTIPLYALPHA = false;
  44382. _this.EMISSIVE = false;
  44383. _this.EMISSIVEDIRECTUV = 0;
  44384. _this.REFLECTIVITY = false;
  44385. _this.REFLECTIVITYDIRECTUV = 0;
  44386. _this.SPECULARTERM = false;
  44387. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44388. _this.MICROSURFACEAUTOMATIC = false;
  44389. _this.LODBASEDMICROSFURACE = false;
  44390. _this.MICROSURFACEMAP = false;
  44391. _this.MICROSURFACEMAPDIRECTUV = 0;
  44392. _this.METALLICWORKFLOW = false;
  44393. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44394. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44395. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44396. _this.AOSTOREINMETALMAPRED = false;
  44397. _this.ENVIRONMENTBRDF = false;
  44398. _this.NORMAL = false;
  44399. _this.TANGENT = false;
  44400. _this.BUMP = false;
  44401. _this.BUMPDIRECTUV = 0;
  44402. _this.OBJECTSPACE_NORMALMAP = false;
  44403. _this.PARALLAX = false;
  44404. _this.PARALLAXOCCLUSION = false;
  44405. _this.NORMALXYSCALE = true;
  44406. _this.LIGHTMAP = false;
  44407. _this.LIGHTMAPDIRECTUV = 0;
  44408. _this.USELIGHTMAPASSHADOWMAP = false;
  44409. _this.GAMMALIGHTMAP = false;
  44410. _this.REFLECTION = false;
  44411. _this.REFLECTIONMAP_3D = false;
  44412. _this.REFLECTIONMAP_SPHERICAL = false;
  44413. _this.REFLECTIONMAP_PLANAR = false;
  44414. _this.REFLECTIONMAP_CUBIC = false;
  44415. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44416. _this.REFLECTIONMAP_PROJECTION = false;
  44417. _this.REFLECTIONMAP_SKYBOX = false;
  44418. _this.REFLECTIONMAP_EXPLICIT = false;
  44419. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44420. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44421. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44422. _this.INVERTCUBICMAP = false;
  44423. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44424. _this.USESPHERICALINVERTEX = false;
  44425. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44426. _this.LODINREFLECTIONALPHA = false;
  44427. _this.GAMMAREFLECTION = false;
  44428. _this.RADIANCEOCCLUSION = false;
  44429. _this.HORIZONOCCLUSION = false;
  44430. _this.REFRACTION = false;
  44431. _this.REFRACTIONMAP_3D = false;
  44432. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44433. _this.LODINREFRACTIONALPHA = false;
  44434. _this.GAMMAREFRACTION = false;
  44435. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44436. _this.INSTANCES = false;
  44437. _this.NUM_BONE_INFLUENCERS = 0;
  44438. _this.BonesPerMesh = 0;
  44439. _this.NONUNIFORMSCALING = false;
  44440. _this.MORPHTARGETS = false;
  44441. _this.MORPHTARGETS_NORMAL = false;
  44442. _this.MORPHTARGETS_TANGENT = false;
  44443. _this.NUM_MORPH_INFLUENCERS = 0;
  44444. _this.IMAGEPROCESSING = false;
  44445. _this.VIGNETTE = false;
  44446. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44447. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44448. _this.TONEMAPPING = false;
  44449. _this.CONTRAST = false;
  44450. _this.COLORCURVES = false;
  44451. _this.COLORGRADING = false;
  44452. _this.COLORGRADING3D = false;
  44453. _this.SAMPLER3DGREENDEPTH = false;
  44454. _this.SAMPLER3DBGRMAP = false;
  44455. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44456. _this.EXPOSURE = false;
  44457. _this.USEPHYSICALLIGHTFALLOFF = false;
  44458. _this.TWOSIDEDLIGHTING = false;
  44459. _this.SHADOWFLOAT = false;
  44460. _this.CLIPPLANE = false;
  44461. _this.POINTSIZE = false;
  44462. _this.FOG = false;
  44463. _this.LOGARITHMICDEPTH = false;
  44464. _this.FORCENORMALFORWARD = false;
  44465. _this.SPECULARAA = false;
  44466. _this.UNLIT = false;
  44467. _this.rebuild();
  44468. return _this;
  44469. }
  44470. /**
  44471. * Resets the PBR Material defines.
  44472. */
  44473. PBRMaterialDefines.prototype.reset = function () {
  44474. _super.prototype.reset.call(this);
  44475. this.ALPHATESTVALUE = "0.5";
  44476. this.PBR = true;
  44477. };
  44478. return PBRMaterialDefines;
  44479. }(BABYLON.MaterialDefines));
  44480. /**
  44481. * The Physically based material base class of BJS.
  44482. *
  44483. * This offers the main features of a standard PBR material.
  44484. * For more information, please refer to the documentation :
  44485. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44486. */
  44487. var PBRBaseMaterial = /** @class */ (function (_super) {
  44488. __extends(PBRBaseMaterial, _super);
  44489. /**
  44490. * Instantiates a new PBRMaterial instance.
  44491. *
  44492. * @param name The material name
  44493. * @param scene The scene the material will be use in.
  44494. */
  44495. function PBRBaseMaterial(name, scene) {
  44496. var _this = _super.call(this, name, scene) || this;
  44497. /**
  44498. * Intensity of the direct lights e.g. the four lights available in your scene.
  44499. * This impacts both the direct diffuse and specular highlights.
  44500. */
  44501. _this._directIntensity = 1.0;
  44502. /**
  44503. * Intensity of the emissive part of the material.
  44504. * This helps controlling the emissive effect without modifying the emissive color.
  44505. */
  44506. _this._emissiveIntensity = 1.0;
  44507. /**
  44508. * Intensity of the environment e.g. how much the environment will light the object
  44509. * either through harmonics for rough material or through the refelction for shiny ones.
  44510. */
  44511. _this._environmentIntensity = 1.0;
  44512. /**
  44513. * This is a special control allowing the reduction of the specular highlights coming from the
  44514. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44515. */
  44516. _this._specularIntensity = 1.0;
  44517. /**
  44518. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44519. */
  44520. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44521. /**
  44522. * Debug Control allowing disabling the bump map on this material.
  44523. */
  44524. _this._disableBumpMap = false;
  44525. /**
  44526. * AKA Occlusion Texture Intensity in other nomenclature.
  44527. */
  44528. _this._ambientTextureStrength = 1.0;
  44529. /**
  44530. * The color of a material in ambient lighting.
  44531. */
  44532. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44533. /**
  44534. * AKA Diffuse Color in other nomenclature.
  44535. */
  44536. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44537. /**
  44538. * AKA Specular Color in other nomenclature.
  44539. */
  44540. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44541. /**
  44542. * The color applied when light is reflected from a material.
  44543. */
  44544. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44545. /**
  44546. * The color applied when light is emitted from a material.
  44547. */
  44548. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44549. /**
  44550. * AKA Glossiness in other nomenclature.
  44551. */
  44552. _this._microSurface = 0.9;
  44553. /**
  44554. * source material index of refraction (IOR)' / 'destination material IOR.
  44555. */
  44556. _this._indexOfRefraction = 0.66;
  44557. /**
  44558. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44559. */
  44560. _this._invertRefractionY = false;
  44561. /**
  44562. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44563. * Materials half opaque for instance using refraction could benefit from this control.
  44564. */
  44565. _this._linkRefractionWithTransparency = false;
  44566. /**
  44567. * Specifies that the material will use the light map as a show map.
  44568. */
  44569. _this._useLightmapAsShadowmap = false;
  44570. /**
  44571. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44572. * makes the reflect vector face the model (under horizon).
  44573. */
  44574. _this._useHorizonOcclusion = true;
  44575. /**
  44576. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44577. * too much the area relying on ambient texture to define their ambient occlusion.
  44578. */
  44579. _this._useRadianceOcclusion = true;
  44580. /**
  44581. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44582. */
  44583. _this._useAlphaFromAlbedoTexture = false;
  44584. /**
  44585. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44586. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44587. */
  44588. _this._useSpecularOverAlpha = true;
  44589. /**
  44590. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44591. */
  44592. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44593. /**
  44594. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44595. */
  44596. _this._useRoughnessFromMetallicTextureAlpha = true;
  44597. /**
  44598. * Specifies if the metallic texture contains the roughness information in its green channel.
  44599. */
  44600. _this._useRoughnessFromMetallicTextureGreen = false;
  44601. /**
  44602. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44603. */
  44604. _this._useMetallnessFromMetallicTextureBlue = false;
  44605. /**
  44606. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44607. */
  44608. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44609. /**
  44610. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44611. */
  44612. _this._useAmbientInGrayScale = false;
  44613. /**
  44614. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44615. * The material will try to infer what glossiness each pixel should be.
  44616. */
  44617. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44618. /**
  44619. * BJS is using an harcoded light falloff based on a manually sets up range.
  44620. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44621. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44622. */
  44623. _this._usePhysicalLightFalloff = true;
  44624. /**
  44625. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44626. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44627. */
  44628. _this._useRadianceOverAlpha = true;
  44629. /**
  44630. * Allows using an object space normal map (instead of tangent space).
  44631. */
  44632. _this._useObjectSpaceNormalMap = false;
  44633. /**
  44634. * Allows using the bump map in parallax mode.
  44635. */
  44636. _this._useParallax = false;
  44637. /**
  44638. * Allows using the bump map in parallax occlusion mode.
  44639. */
  44640. _this._useParallaxOcclusion = false;
  44641. /**
  44642. * Controls the scale bias of the parallax mode.
  44643. */
  44644. _this._parallaxScaleBias = 0.05;
  44645. /**
  44646. * If sets to true, disables all the lights affecting the material.
  44647. */
  44648. _this._disableLighting = false;
  44649. /**
  44650. * Number of Simultaneous lights allowed on the material.
  44651. */
  44652. _this._maxSimultaneousLights = 4;
  44653. /**
  44654. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44655. */
  44656. _this._invertNormalMapX = false;
  44657. /**
  44658. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44659. */
  44660. _this._invertNormalMapY = false;
  44661. /**
  44662. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44663. */
  44664. _this._twoSidedLighting = false;
  44665. /**
  44666. * Defines the alpha limits in alpha test mode.
  44667. */
  44668. _this._alphaCutOff = 0.4;
  44669. /**
  44670. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44671. */
  44672. _this._forceAlphaTest = false;
  44673. /**
  44674. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44675. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44676. */
  44677. _this._useAlphaFresnel = false;
  44678. /**
  44679. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44680. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44681. */
  44682. _this._useLinearAlphaFresnel = false;
  44683. /**
  44684. * The transparency mode of the material.
  44685. */
  44686. _this._transparencyMode = null;
  44687. /**
  44688. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44689. * from cos thetav and roughness:
  44690. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44691. */
  44692. _this._environmentBRDFTexture = null;
  44693. /**
  44694. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44695. */
  44696. _this._forceIrradianceInFragment = false;
  44697. /**
  44698. * Force normal to face away from face.
  44699. */
  44700. _this._forceNormalForward = false;
  44701. /**
  44702. * Enables specular anti aliasing in the PBR shader.
  44703. * It will both interacts on the Geometry for analytical and IBL lighting.
  44704. * It also prefilter the roughness map based on the bump values.
  44705. */
  44706. _this._enableSpecularAntiAliasing = false;
  44707. /**
  44708. * Stores the available render targets.
  44709. */
  44710. _this._renderTargets = new BABYLON.SmartArray(16);
  44711. /**
  44712. * Sets the global ambient color for the material used in lighting calculations.
  44713. */
  44714. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44715. /**
  44716. * If set to true, no lighting calculations will be applied.
  44717. */
  44718. _this._unlit = false;
  44719. // Setup the default processing configuration to the scene.
  44720. _this._attachImageProcessingConfiguration(null);
  44721. _this.getRenderTargetTextures = function () {
  44722. _this._renderTargets.reset();
  44723. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44724. _this._renderTargets.push(_this._reflectionTexture);
  44725. }
  44726. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44727. _this._renderTargets.push(_this._refractionTexture);
  44728. }
  44729. return _this._renderTargets;
  44730. };
  44731. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44732. return _this;
  44733. }
  44734. /**
  44735. * Attaches a new image processing configuration to the PBR Material.
  44736. * @param configuration
  44737. */
  44738. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44739. var _this = this;
  44740. if (configuration === this._imageProcessingConfiguration) {
  44741. return;
  44742. }
  44743. // Detaches observer.
  44744. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44745. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44746. }
  44747. // Pick the scene configuration if needed.
  44748. if (!configuration) {
  44749. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44750. }
  44751. else {
  44752. this._imageProcessingConfiguration = configuration;
  44753. }
  44754. // Attaches observer.
  44755. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44756. _this._markAllSubMeshesAsImageProcessingDirty();
  44757. });
  44758. };
  44759. /**
  44760. * Gets the name of the material class.
  44761. */
  44762. PBRBaseMaterial.prototype.getClassName = function () {
  44763. return "PBRBaseMaterial";
  44764. };
  44765. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44766. /**
  44767. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44768. */
  44769. get: function () {
  44770. return this._useLogarithmicDepth;
  44771. },
  44772. /**
  44773. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44774. */
  44775. set: function (value) {
  44776. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44777. },
  44778. enumerable: true,
  44779. configurable: true
  44780. });
  44781. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44782. /**
  44783. * Gets the current transparency mode.
  44784. */
  44785. get: function () {
  44786. return this._transparencyMode;
  44787. },
  44788. /**
  44789. * Sets the transparency mode of the material.
  44790. */
  44791. set: function (value) {
  44792. if (this._transparencyMode === value) {
  44793. return;
  44794. }
  44795. this._transparencyMode = value;
  44796. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44797. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44798. },
  44799. enumerable: true,
  44800. configurable: true
  44801. });
  44802. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44803. /**
  44804. * Returns true if alpha blending should be disabled.
  44805. */
  44806. get: function () {
  44807. return (this._linkRefractionWithTransparency ||
  44808. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44809. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44810. },
  44811. enumerable: true,
  44812. configurable: true
  44813. });
  44814. /**
  44815. * Specifies whether or not this material should be rendered in alpha blend mode.
  44816. */
  44817. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44818. if (this._disableAlphaBlending) {
  44819. return false;
  44820. }
  44821. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44822. };
  44823. /**
  44824. * Specifies if the mesh will require alpha blending.
  44825. * @param mesh - BJS mesh.
  44826. */
  44827. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44828. if (this._disableAlphaBlending) {
  44829. return false;
  44830. }
  44831. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44832. };
  44833. /**
  44834. * Specifies whether or not this material should be rendered in alpha test mode.
  44835. */
  44836. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44837. if (this._forceAlphaTest) {
  44838. return true;
  44839. }
  44840. if (this._linkRefractionWithTransparency) {
  44841. return false;
  44842. }
  44843. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44844. };
  44845. /**
  44846. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44847. */
  44848. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44849. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44850. };
  44851. /**
  44852. * Gets the texture used for the alpha test.
  44853. */
  44854. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44855. return this._albedoTexture;
  44856. };
  44857. /**
  44858. * Specifies that the submesh is ready to be used.
  44859. * @param mesh - BJS mesh.
  44860. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44861. * @param useInstances - Specifies that instances should be used.
  44862. * @returns - boolean indicating that the submesh is ready or not.
  44863. */
  44864. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44865. if (subMesh.effect && this.isFrozen) {
  44866. if (this._wasPreviouslyReady) {
  44867. return true;
  44868. }
  44869. }
  44870. if (!subMesh._materialDefines) {
  44871. subMesh._materialDefines = new PBRMaterialDefines();
  44872. }
  44873. var defines = subMesh._materialDefines;
  44874. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44875. if (defines._renderId === this.getScene().getRenderId()) {
  44876. return true;
  44877. }
  44878. }
  44879. var scene = this.getScene();
  44880. var engine = scene.getEngine();
  44881. if (defines._areTexturesDirty) {
  44882. if (scene.texturesEnabled) {
  44883. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44884. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44885. return false;
  44886. }
  44887. }
  44888. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44889. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44890. return false;
  44891. }
  44892. }
  44893. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44894. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44895. return false;
  44896. }
  44897. }
  44898. var reflectionTexture = this._getReflectionTexture();
  44899. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44900. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44901. return false;
  44902. }
  44903. }
  44904. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44905. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44906. return false;
  44907. }
  44908. }
  44909. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44910. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44911. return false;
  44912. }
  44913. }
  44914. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44915. if (this._metallicTexture) {
  44916. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44917. return false;
  44918. }
  44919. }
  44920. else if (this._reflectivityTexture) {
  44921. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44922. return false;
  44923. }
  44924. }
  44925. if (this._microSurfaceTexture) {
  44926. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44927. return false;
  44928. }
  44929. }
  44930. }
  44931. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44932. // Bump texture cannot be not blocking.
  44933. if (!this._bumpTexture.isReady()) {
  44934. return false;
  44935. }
  44936. }
  44937. var refractionTexture = this._getRefractionTexture();
  44938. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44939. if (!refractionTexture.isReadyOrNotBlocking()) {
  44940. return false;
  44941. }
  44942. }
  44943. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44944. // This is blocking.
  44945. if (!this._environmentBRDFTexture.isReady()) {
  44946. return false;
  44947. }
  44948. }
  44949. }
  44950. }
  44951. if (defines._areImageProcessingDirty) {
  44952. if (!this._imageProcessingConfiguration.isReady()) {
  44953. return false;
  44954. }
  44955. }
  44956. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44957. mesh.createNormals(true);
  44958. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44959. }
  44960. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44961. if (effect) {
  44962. scene.resetCachedMaterial();
  44963. subMesh.setEffect(effect, defines);
  44964. this.buildUniformLayout();
  44965. }
  44966. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44967. return false;
  44968. }
  44969. defines._renderId = scene.getRenderId();
  44970. this._wasPreviouslyReady = true;
  44971. return true;
  44972. };
  44973. /**
  44974. * Specifies if the material uses metallic roughness workflow.
  44975. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44976. */
  44977. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44978. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44979. return true;
  44980. }
  44981. return false;
  44982. };
  44983. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44984. if (onCompiled === void 0) { onCompiled = null; }
  44985. if (onError === void 0) { onError = null; }
  44986. if (useInstances === void 0) { useInstances = null; }
  44987. if (useClipPlane === void 0) { useClipPlane = null; }
  44988. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44989. if (!defines.isDirty) {
  44990. return null;
  44991. }
  44992. defines.markAsProcessed();
  44993. var scene = this.getScene();
  44994. var engine = scene.getEngine();
  44995. // Fallbacks
  44996. var fallbacks = new BABYLON.EffectFallbacks();
  44997. var fallbackRank = 0;
  44998. if (defines.USESPHERICALINVERTEX) {
  44999. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45000. }
  45001. if (defines.FOG) {
  45002. fallbacks.addFallback(fallbackRank, "FOG");
  45003. }
  45004. if (defines.SPECULARAA) {
  45005. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45006. }
  45007. if (defines.POINTSIZE) {
  45008. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45009. }
  45010. if (defines.LOGARITHMICDEPTH) {
  45011. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45012. }
  45013. if (defines.PARALLAX) {
  45014. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45015. }
  45016. if (defines.PARALLAXOCCLUSION) {
  45017. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45018. }
  45019. if (defines.ENVIRONMENTBRDF) {
  45020. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45021. }
  45022. if (defines.TANGENT) {
  45023. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45024. }
  45025. if (defines.BUMP) {
  45026. fallbacks.addFallback(fallbackRank++, "BUMP");
  45027. }
  45028. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45029. if (defines.SPECULARTERM) {
  45030. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45031. }
  45032. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45033. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45034. }
  45035. if (defines.LIGHTMAP) {
  45036. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45037. }
  45038. if (defines.NORMAL) {
  45039. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45040. }
  45041. if (defines.AMBIENT) {
  45042. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45043. }
  45044. if (defines.EMISSIVE) {
  45045. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45046. }
  45047. if (defines.VERTEXCOLOR) {
  45048. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45049. }
  45050. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45051. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45052. }
  45053. if (defines.MORPHTARGETS) {
  45054. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45055. }
  45056. //Attributes
  45057. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45058. if (defines.NORMAL) {
  45059. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45060. }
  45061. if (defines.TANGENT) {
  45062. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45063. }
  45064. if (defines.UV1) {
  45065. attribs.push(BABYLON.VertexBuffer.UVKind);
  45066. }
  45067. if (defines.UV2) {
  45068. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45069. }
  45070. if (defines.VERTEXCOLOR) {
  45071. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45072. }
  45073. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45074. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45075. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45076. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45077. "vFogInfos", "vFogColor", "pointSize",
  45078. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45079. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45080. "mBones",
  45081. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45082. "vLightingIntensity",
  45083. "logarithmicDepthConstant",
  45084. "vSphericalX", "vSphericalY", "vSphericalZ",
  45085. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45086. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45087. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45088. "vTangentSpaceParams"
  45089. ];
  45090. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45091. "bumpSampler", "lightmapSampler", "opacitySampler",
  45092. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45093. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45094. "microSurfaceSampler", "environmentBrdfSampler"];
  45095. var uniformBuffers = ["Material", "Scene"];
  45096. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45097. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45098. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45099. uniformsNames: uniforms,
  45100. uniformBuffersNames: uniformBuffers,
  45101. samplers: samplers,
  45102. defines: defines,
  45103. maxSimultaneousLights: this._maxSimultaneousLights
  45104. });
  45105. var join = defines.toString();
  45106. return engine.createEffect("pbr", {
  45107. attributes: attribs,
  45108. uniformsNames: uniforms,
  45109. uniformBuffersNames: uniformBuffers,
  45110. samplers: samplers,
  45111. defines: join,
  45112. fallbacks: fallbacks,
  45113. onCompiled: onCompiled,
  45114. onError: onError,
  45115. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45116. }, engine);
  45117. };
  45118. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45119. if (useInstances === void 0) { useInstances = null; }
  45120. if (useClipPlane === void 0) { useClipPlane = null; }
  45121. var scene = this.getScene();
  45122. var engine = scene.getEngine();
  45123. // Lights
  45124. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45125. defines._needNormals = true;
  45126. // Textures
  45127. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45128. if (defines._areTexturesDirty) {
  45129. defines._needUVs = false;
  45130. if (scene.texturesEnabled) {
  45131. if (scene.getEngine().getCaps().textureLOD) {
  45132. defines.LODBASEDMICROSFURACE = true;
  45133. }
  45134. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45135. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45136. }
  45137. else {
  45138. defines.ALBEDO = false;
  45139. }
  45140. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45141. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45142. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45143. }
  45144. else {
  45145. defines.AMBIENT = false;
  45146. }
  45147. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45148. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45149. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45150. }
  45151. else {
  45152. defines.OPACITY = false;
  45153. }
  45154. var reflectionTexture = this._getReflectionTexture();
  45155. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45156. defines.REFLECTION = true;
  45157. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45158. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45159. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45160. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45161. defines.INVERTCUBICMAP = true;
  45162. }
  45163. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45164. switch (reflectionTexture.coordinatesMode) {
  45165. case BABYLON.Texture.EXPLICIT_MODE:
  45166. defines.REFLECTIONMAP_EXPLICIT = true;
  45167. break;
  45168. case BABYLON.Texture.PLANAR_MODE:
  45169. defines.REFLECTIONMAP_PLANAR = true;
  45170. break;
  45171. case BABYLON.Texture.PROJECTION_MODE:
  45172. defines.REFLECTIONMAP_PROJECTION = true;
  45173. break;
  45174. case BABYLON.Texture.SKYBOX_MODE:
  45175. defines.REFLECTIONMAP_SKYBOX = true;
  45176. break;
  45177. case BABYLON.Texture.SPHERICAL_MODE:
  45178. defines.REFLECTIONMAP_SPHERICAL = true;
  45179. break;
  45180. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45181. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45182. break;
  45183. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45184. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45185. break;
  45186. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45187. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45188. break;
  45189. case BABYLON.Texture.CUBIC_MODE:
  45190. case BABYLON.Texture.INVCUBIC_MODE:
  45191. default:
  45192. defines.REFLECTIONMAP_CUBIC = true;
  45193. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45194. break;
  45195. }
  45196. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45197. if (reflectionTexture.sphericalPolynomial) {
  45198. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45199. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45200. defines.USESPHERICALINVERTEX = false;
  45201. }
  45202. else {
  45203. defines.USESPHERICALINVERTEX = true;
  45204. }
  45205. }
  45206. }
  45207. }
  45208. else {
  45209. defines.REFLECTION = false;
  45210. defines.REFLECTIONMAP_3D = false;
  45211. defines.REFLECTIONMAP_SPHERICAL = false;
  45212. defines.REFLECTIONMAP_PLANAR = false;
  45213. defines.REFLECTIONMAP_CUBIC = false;
  45214. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45215. defines.REFLECTIONMAP_PROJECTION = false;
  45216. defines.REFLECTIONMAP_SKYBOX = false;
  45217. defines.REFLECTIONMAP_EXPLICIT = false;
  45218. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45219. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45220. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45221. defines.INVERTCUBICMAP = false;
  45222. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45223. defines.USESPHERICALINVERTEX = false;
  45224. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45225. defines.LODINREFLECTIONALPHA = false;
  45226. defines.GAMMAREFLECTION = false;
  45227. }
  45228. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45229. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45230. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45231. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45232. }
  45233. else {
  45234. defines.LIGHTMAP = false;
  45235. }
  45236. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45238. }
  45239. else {
  45240. defines.EMISSIVE = false;
  45241. }
  45242. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45243. if (this._metallicTexture) {
  45244. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45245. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45246. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45247. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45248. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45249. }
  45250. else if (this._reflectivityTexture) {
  45251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45252. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45253. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45254. }
  45255. else {
  45256. defines.REFLECTIVITY = false;
  45257. }
  45258. if (this._microSurfaceTexture) {
  45259. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45260. }
  45261. else {
  45262. defines.MICROSURFACEMAP = false;
  45263. }
  45264. }
  45265. else {
  45266. defines.REFLECTIVITY = false;
  45267. defines.MICROSURFACEMAP = false;
  45268. }
  45269. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45270. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45271. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45272. defines.PARALLAX = true;
  45273. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45274. }
  45275. else {
  45276. defines.PARALLAX = false;
  45277. }
  45278. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45279. }
  45280. else {
  45281. defines.BUMP = false;
  45282. }
  45283. var refractionTexture = this._getRefractionTexture();
  45284. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45285. defines.REFRACTION = true;
  45286. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45287. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45288. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45289. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45290. if (this._linkRefractionWithTransparency) {
  45291. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45292. }
  45293. }
  45294. else {
  45295. defines.REFRACTION = false;
  45296. }
  45297. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45298. defines.ENVIRONMENTBRDF = true;
  45299. }
  45300. else {
  45301. defines.ENVIRONMENTBRDF = false;
  45302. }
  45303. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45304. defines.ALPHAFROMALBEDO = true;
  45305. }
  45306. else {
  45307. defines.ALPHAFROMALBEDO = false;
  45308. }
  45309. }
  45310. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45311. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45312. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45313. if (!this.backFaceCulling && this._twoSidedLighting) {
  45314. defines.TWOSIDEDLIGHTING = true;
  45315. }
  45316. else {
  45317. defines.TWOSIDEDLIGHTING = false;
  45318. }
  45319. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45320. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45321. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45322. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45323. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45324. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45325. }
  45326. if (defines._areImageProcessingDirty) {
  45327. this._imageProcessingConfiguration.prepareDefines(defines);
  45328. }
  45329. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45330. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45331. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45332. // Misc.
  45333. if (defines._areMiscDirty) {
  45334. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45335. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45336. }
  45337. // Values that need to be evaluated on every frame
  45338. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45339. // Attribs
  45340. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45341. };
  45342. /**
  45343. * Force shader compilation
  45344. */
  45345. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45346. var _this = this;
  45347. var localOptions = __assign({ clipPlane: false }, options);
  45348. var defines = new PBRMaterialDefines();
  45349. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45350. if (effect.isReady()) {
  45351. if (onCompiled) {
  45352. onCompiled(this);
  45353. }
  45354. }
  45355. else {
  45356. effect.onCompileObservable.add(function () {
  45357. if (onCompiled) {
  45358. onCompiled(_this);
  45359. }
  45360. });
  45361. }
  45362. };
  45363. /**
  45364. * Initializes the uniform buffer layout for the shader.
  45365. */
  45366. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45367. // Order is important !
  45368. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45369. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45370. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45371. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45372. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45373. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45374. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45375. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45376. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45377. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45378. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45379. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45380. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45381. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45382. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45383. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45384. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45385. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45386. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45387. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45388. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45389. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45390. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45391. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45392. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45393. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45394. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45395. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45396. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45397. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45398. this._uniformBuffer.addUniform("pointSize", 1);
  45399. this._uniformBuffer.create();
  45400. };
  45401. /**
  45402. * Unbinds the textures.
  45403. */
  45404. PBRBaseMaterial.prototype.unbind = function () {
  45405. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45406. this._uniformBuffer.setTexture("reflectionSampler", null);
  45407. }
  45408. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45409. this._uniformBuffer.setTexture("refractionSampler", null);
  45410. }
  45411. _super.prototype.unbind.call(this);
  45412. };
  45413. /**
  45414. * Binds the submesh data.
  45415. * @param world - The world matrix.
  45416. * @param mesh - The BJS mesh.
  45417. * @param subMesh - A submesh of the BJS mesh.
  45418. */
  45419. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45420. var scene = this.getScene();
  45421. var defines = subMesh._materialDefines;
  45422. if (!defines) {
  45423. return;
  45424. }
  45425. var effect = subMesh.effect;
  45426. if (!effect) {
  45427. return;
  45428. }
  45429. this._activeEffect = effect;
  45430. // Matrices
  45431. this.bindOnlyWorldMatrix(world);
  45432. // Normal Matrix
  45433. if (defines.OBJECTSPACE_NORMALMAP) {
  45434. world.toNormalMatrix(this._normalMatrix);
  45435. this.bindOnlyNormalMatrix(this._normalMatrix);
  45436. }
  45437. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45438. // Bones
  45439. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45440. var reflectionTexture = null;
  45441. if (mustRebind) {
  45442. this._uniformBuffer.bindToEffect(effect, "Material");
  45443. this.bindViewProjection(effect);
  45444. reflectionTexture = this._getReflectionTexture();
  45445. var refractionTexture = this._getRefractionTexture();
  45446. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45447. // Texture uniforms
  45448. if (scene.texturesEnabled) {
  45449. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45450. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45451. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45452. }
  45453. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45454. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45455. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45456. }
  45457. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45458. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45459. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45460. }
  45461. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45462. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45463. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45464. if (reflectionTexture.boundingBoxSize) {
  45465. var cubeTexture = reflectionTexture;
  45466. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45467. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45468. }
  45469. var polynomials = reflectionTexture.sphericalPolynomial;
  45470. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45471. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45472. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45473. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45474. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45475. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45476. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45477. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45478. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45479. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45480. }
  45481. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45482. }
  45483. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45484. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45485. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45486. }
  45487. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45488. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45489. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45490. }
  45491. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45492. if (this._metallicTexture) {
  45493. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45494. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45495. }
  45496. else if (this._reflectivityTexture) {
  45497. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45498. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45499. }
  45500. if (this._microSurfaceTexture) {
  45501. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45502. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45503. }
  45504. }
  45505. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45506. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45507. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45508. if (scene._mirroredCameraPosition) {
  45509. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45510. }
  45511. else {
  45512. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45513. }
  45514. }
  45515. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45516. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45517. var depth = 1.0;
  45518. if (!refractionTexture.isCube) {
  45519. if (refractionTexture.depth) {
  45520. depth = refractionTexture.depth;
  45521. }
  45522. }
  45523. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45524. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45525. }
  45526. }
  45527. // Point size
  45528. if (this.pointsCloud) {
  45529. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45530. }
  45531. // Colors
  45532. if (defines.METALLICWORKFLOW) {
  45533. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45534. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45535. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45536. }
  45537. else {
  45538. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45539. }
  45540. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45541. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45542. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45543. // Misc
  45544. this._lightingInfos.x = this._directIntensity;
  45545. this._lightingInfos.y = this._emissiveIntensity;
  45546. this._lightingInfos.z = this._environmentIntensity;
  45547. this._lightingInfos.w = this._specularIntensity;
  45548. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45549. }
  45550. // Textures
  45551. if (scene.texturesEnabled) {
  45552. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45553. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45554. }
  45555. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45556. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45557. }
  45558. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45559. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45560. }
  45561. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45562. if (defines.LODBASEDMICROSFURACE) {
  45563. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45564. }
  45565. else {
  45566. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45567. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45568. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45569. }
  45570. }
  45571. if (defines.ENVIRONMENTBRDF) {
  45572. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45573. }
  45574. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45575. if (defines.LODBASEDMICROSFURACE) {
  45576. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45577. }
  45578. else {
  45579. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45580. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45581. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45582. }
  45583. }
  45584. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45585. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45586. }
  45587. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45588. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45589. }
  45590. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45591. if (this._metallicTexture) {
  45592. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45593. }
  45594. else if (this._reflectivityTexture) {
  45595. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45596. }
  45597. if (this._microSurfaceTexture) {
  45598. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45599. }
  45600. }
  45601. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45602. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45603. }
  45604. }
  45605. // Clip plane
  45606. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45607. // Colors
  45608. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45609. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45610. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45611. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45612. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45613. }
  45614. if (mustRebind || !this.isFrozen) {
  45615. // Lights
  45616. if (scene.lightsEnabled && !this._disableLighting) {
  45617. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45618. }
  45619. // View
  45620. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45621. this.bindView(effect);
  45622. }
  45623. // Fog
  45624. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45625. // Morph targets
  45626. if (defines.NUM_MORPH_INFLUENCERS) {
  45627. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45628. }
  45629. // image processing
  45630. this._imageProcessingConfiguration.bind(this._activeEffect);
  45631. // Log. depth
  45632. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45633. }
  45634. this._uniformBuffer.update();
  45635. this._afterBind(mesh, this._activeEffect);
  45636. };
  45637. /**
  45638. * Returns the animatable textures.
  45639. * @returns - Array of animatable textures.
  45640. */
  45641. PBRBaseMaterial.prototype.getAnimatables = function () {
  45642. var results = [];
  45643. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45644. results.push(this._albedoTexture);
  45645. }
  45646. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45647. results.push(this._ambientTexture);
  45648. }
  45649. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45650. results.push(this._opacityTexture);
  45651. }
  45652. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45653. results.push(this._reflectionTexture);
  45654. }
  45655. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45656. results.push(this._emissiveTexture);
  45657. }
  45658. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45659. results.push(this._metallicTexture);
  45660. }
  45661. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45662. results.push(this._reflectivityTexture);
  45663. }
  45664. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45665. results.push(this._bumpTexture);
  45666. }
  45667. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45668. results.push(this._lightmapTexture);
  45669. }
  45670. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45671. results.push(this._refractionTexture);
  45672. }
  45673. return results;
  45674. };
  45675. /**
  45676. * Returns the texture used for reflections.
  45677. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45678. */
  45679. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45680. if (this._reflectionTexture) {
  45681. return this._reflectionTexture;
  45682. }
  45683. return this.getScene().environmentTexture;
  45684. };
  45685. /**
  45686. * Returns the texture used for refraction or null if none is used.
  45687. * @returns - Refection texture if present. If no refraction texture and refraction
  45688. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45689. */
  45690. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45691. if (this._refractionTexture) {
  45692. return this._refractionTexture;
  45693. }
  45694. if (this._linkRefractionWithTransparency) {
  45695. return this.getScene().environmentTexture;
  45696. }
  45697. return null;
  45698. };
  45699. /**
  45700. * Disposes the resources of the material.
  45701. * @param forceDisposeEffect - Forces the disposal of effects.
  45702. * @param forceDisposeTextures - Forces the disposal of all textures.
  45703. */
  45704. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45705. if (forceDisposeTextures) {
  45706. if (this._albedoTexture) {
  45707. this._albedoTexture.dispose();
  45708. }
  45709. if (this._ambientTexture) {
  45710. this._ambientTexture.dispose();
  45711. }
  45712. if (this._opacityTexture) {
  45713. this._opacityTexture.dispose();
  45714. }
  45715. if (this._reflectionTexture) {
  45716. this._reflectionTexture.dispose();
  45717. }
  45718. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45719. this._environmentBRDFTexture.dispose();
  45720. }
  45721. if (this._emissiveTexture) {
  45722. this._emissiveTexture.dispose();
  45723. }
  45724. if (this._metallicTexture) {
  45725. this._metallicTexture.dispose();
  45726. }
  45727. if (this._reflectivityTexture) {
  45728. this._reflectivityTexture.dispose();
  45729. }
  45730. if (this._bumpTexture) {
  45731. this._bumpTexture.dispose();
  45732. }
  45733. if (this._lightmapTexture) {
  45734. this._lightmapTexture.dispose();
  45735. }
  45736. if (this._refractionTexture) {
  45737. this._refractionTexture.dispose();
  45738. }
  45739. }
  45740. this._renderTargets.dispose();
  45741. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45742. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45743. }
  45744. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45745. };
  45746. /**
  45747. * Stores the reflectivity values based on metallic roughness workflow.
  45748. */
  45749. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45750. __decorate([
  45751. BABYLON.serializeAsImageProcessingConfiguration()
  45752. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45753. __decorate([
  45754. BABYLON.serialize()
  45755. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45756. __decorate([
  45757. BABYLON.serialize()
  45758. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45759. return PBRBaseMaterial;
  45760. }(BABYLON.PushMaterial));
  45761. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45762. })(BABYLON || (BABYLON = {}));
  45763. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45764. var BABYLON;
  45765. (function (BABYLON) {
  45766. /**
  45767. * The Physically based simple base material of BJS.
  45768. *
  45769. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45770. * It is used as the base class for both the specGloss and metalRough conventions.
  45771. */
  45772. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45773. __extends(PBRBaseSimpleMaterial, _super);
  45774. /**
  45775. * Instantiates a new PBRMaterial instance.
  45776. *
  45777. * @param name The material name
  45778. * @param scene The scene the material will be use in.
  45779. */
  45780. function PBRBaseSimpleMaterial(name, scene) {
  45781. var _this = _super.call(this, name, scene) || this;
  45782. /**
  45783. * Number of Simultaneous lights allowed on the material.
  45784. */
  45785. _this.maxSimultaneousLights = 4;
  45786. /**
  45787. * If sets to true, disables all the lights affecting the material.
  45788. */
  45789. _this.disableLighting = false;
  45790. /**
  45791. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45792. */
  45793. _this.invertNormalMapX = false;
  45794. /**
  45795. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45796. */
  45797. _this.invertNormalMapY = false;
  45798. /**
  45799. * Emissivie color used to self-illuminate the model.
  45800. */
  45801. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45802. /**
  45803. * Occlusion Channel Strenght.
  45804. */
  45805. _this.occlusionStrength = 1.0;
  45806. _this.useLightmapAsShadowmap = false;
  45807. _this._useAlphaFromAlbedoTexture = true;
  45808. _this._useAmbientInGrayScale = true;
  45809. return _this;
  45810. }
  45811. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45812. /**
  45813. * Gets the current double sided mode.
  45814. */
  45815. get: function () {
  45816. return this._twoSidedLighting;
  45817. },
  45818. /**
  45819. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45820. */
  45821. set: function (value) {
  45822. if (this._twoSidedLighting === value) {
  45823. return;
  45824. }
  45825. this._twoSidedLighting = value;
  45826. this.backFaceCulling = !value;
  45827. this._markAllSubMeshesAsTexturesDirty();
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. /**
  45833. * Return the active textures of the material.
  45834. */
  45835. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45836. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45837. if (this.environmentTexture) {
  45838. activeTextures.push(this.environmentTexture);
  45839. }
  45840. if (this.normalTexture) {
  45841. activeTextures.push(this.normalTexture);
  45842. }
  45843. if (this.emissiveTexture) {
  45844. activeTextures.push(this.emissiveTexture);
  45845. }
  45846. if (this.occlusionTexture) {
  45847. activeTextures.push(this.occlusionTexture);
  45848. }
  45849. if (this.lightmapTexture) {
  45850. activeTextures.push(this.lightmapTexture);
  45851. }
  45852. return activeTextures;
  45853. };
  45854. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45855. if (_super.prototype.hasTexture.call(this, texture)) {
  45856. return true;
  45857. }
  45858. if (this.lightmapTexture === texture) {
  45859. return true;
  45860. }
  45861. return false;
  45862. };
  45863. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45864. return "PBRBaseSimpleMaterial";
  45865. };
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45869. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45873. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45874. __decorate([
  45875. BABYLON.serializeAsTexture(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45877. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45878. __decorate([
  45879. BABYLON.serialize(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45886. __decorate([
  45887. BABYLON.serializeAsTexture(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45889. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45890. __decorate([
  45891. BABYLON.serializeAsColor3("emissive"),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsTexture(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45898. __decorate([
  45899. BABYLON.serialize(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45901. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45902. __decorate([
  45903. BABYLON.serializeAsTexture(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45905. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45906. __decorate([
  45907. BABYLON.serialize(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45909. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45910. __decorate([
  45911. BABYLON.serialize()
  45912. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45913. __decorate([
  45914. BABYLON.serializeAsTexture(),
  45915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45916. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45917. __decorate([
  45918. BABYLON.serialize(),
  45919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45920. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45921. return PBRBaseSimpleMaterial;
  45922. }(BABYLON.PBRBaseMaterial));
  45923. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45924. })(BABYLON || (BABYLON = {}));
  45925. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45926. var BABYLON;
  45927. (function (BABYLON) {
  45928. /**
  45929. * The Physically based material of BJS.
  45930. *
  45931. * This offers the main features of a standard PBR material.
  45932. * For more information, please refer to the documentation :
  45933. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45934. */
  45935. var PBRMaterial = /** @class */ (function (_super) {
  45936. __extends(PBRMaterial, _super);
  45937. /**
  45938. * Instantiates a new PBRMaterial instance.
  45939. *
  45940. * @param name The material name
  45941. * @param scene The scene the material will be use in.
  45942. */
  45943. function PBRMaterial(name, scene) {
  45944. var _this = _super.call(this, name, scene) || this;
  45945. /**
  45946. * Intensity of the direct lights e.g. the four lights available in your scene.
  45947. * This impacts both the direct diffuse and specular highlights.
  45948. */
  45949. _this.directIntensity = 1.0;
  45950. /**
  45951. * Intensity of the emissive part of the material.
  45952. * This helps controlling the emissive effect without modifying the emissive color.
  45953. */
  45954. _this.emissiveIntensity = 1.0;
  45955. /**
  45956. * Intensity of the environment e.g. how much the environment will light the object
  45957. * either through harmonics for rough material or through the refelction for shiny ones.
  45958. */
  45959. _this.environmentIntensity = 1.0;
  45960. /**
  45961. * This is a special control allowing the reduction of the specular highlights coming from the
  45962. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45963. */
  45964. _this.specularIntensity = 1.0;
  45965. /**
  45966. * Debug Control allowing disabling the bump map on this material.
  45967. */
  45968. _this.disableBumpMap = false;
  45969. /**
  45970. * AKA Occlusion Texture Intensity in other nomenclature.
  45971. */
  45972. _this.ambientTextureStrength = 1.0;
  45973. /**
  45974. * The color of a material in ambient lighting.
  45975. */
  45976. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45977. /**
  45978. * AKA Diffuse Color in other nomenclature.
  45979. */
  45980. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45981. /**
  45982. * AKA Specular Color in other nomenclature.
  45983. */
  45984. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45985. /**
  45986. * The color reflected from the material.
  45987. */
  45988. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45989. /**
  45990. * The color emitted from the material.
  45991. */
  45992. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45993. /**
  45994. * AKA Glossiness in other nomenclature.
  45995. */
  45996. _this.microSurface = 1.0;
  45997. /**
  45998. * source material index of refraction (IOR)' / 'destination material IOR.
  45999. */
  46000. _this.indexOfRefraction = 0.66;
  46001. /**
  46002. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46003. */
  46004. _this.invertRefractionY = false;
  46005. /**
  46006. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46007. * Materials half opaque for instance using refraction could benefit from this control.
  46008. */
  46009. _this.linkRefractionWithTransparency = false;
  46010. _this.useLightmapAsShadowmap = false;
  46011. /**
  46012. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46013. */
  46014. _this.useAlphaFromAlbedoTexture = false;
  46015. /**
  46016. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46017. */
  46018. _this.forceAlphaTest = false;
  46019. /**
  46020. * Defines the alpha limits in alpha test mode.
  46021. */
  46022. _this.alphaCutOff = 0.4;
  46023. /**
  46024. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46025. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46026. */
  46027. _this.useSpecularOverAlpha = true;
  46028. /**
  46029. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46030. */
  46031. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46032. /**
  46033. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46034. */
  46035. _this.useRoughnessFromMetallicTextureAlpha = true;
  46036. /**
  46037. * Specifies if the metallic texture contains the roughness information in its green channel.
  46038. */
  46039. _this.useRoughnessFromMetallicTextureGreen = false;
  46040. /**
  46041. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46042. */
  46043. _this.useMetallnessFromMetallicTextureBlue = false;
  46044. /**
  46045. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46046. */
  46047. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46048. /**
  46049. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46050. */
  46051. _this.useAmbientInGrayScale = false;
  46052. /**
  46053. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46054. * The material will try to infer what glossiness each pixel should be.
  46055. */
  46056. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46057. /**
  46058. * BJS is using an harcoded light falloff based on a manually sets up range.
  46059. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46060. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46061. */
  46062. _this.usePhysicalLightFalloff = true;
  46063. /**
  46064. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46065. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46066. */
  46067. _this.useRadianceOverAlpha = true;
  46068. /**
  46069. * Allows using an object space normal map (instead of tangent space).
  46070. */
  46071. _this.useObjectSpaceNormalMap = false;
  46072. /**
  46073. * Allows using the bump map in parallax mode.
  46074. */
  46075. _this.useParallax = false;
  46076. /**
  46077. * Allows using the bump map in parallax occlusion mode.
  46078. */
  46079. _this.useParallaxOcclusion = false;
  46080. /**
  46081. * Controls the scale bias of the parallax mode.
  46082. */
  46083. _this.parallaxScaleBias = 0.05;
  46084. /**
  46085. * If sets to true, disables all the lights affecting the material.
  46086. */
  46087. _this.disableLighting = false;
  46088. /**
  46089. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46090. */
  46091. _this.forceIrradianceInFragment = false;
  46092. /**
  46093. * Number of Simultaneous lights allowed on the material.
  46094. */
  46095. _this.maxSimultaneousLights = 4;
  46096. /**
  46097. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46098. */
  46099. _this.invertNormalMapX = false;
  46100. /**
  46101. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46102. */
  46103. _this.invertNormalMapY = false;
  46104. /**
  46105. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46106. */
  46107. _this.twoSidedLighting = false;
  46108. /**
  46109. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46110. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46111. */
  46112. _this.useAlphaFresnel = false;
  46113. /**
  46114. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46115. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46116. */
  46117. _this.useLinearAlphaFresnel = false;
  46118. /**
  46119. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46120. * And/Or occlude the blended part.
  46121. */
  46122. _this.environmentBRDFTexture = null;
  46123. /**
  46124. * Force normal to face away from face.
  46125. */
  46126. _this.forceNormalForward = false;
  46127. /**
  46128. * Enables specular anti aliasing in the PBR shader.
  46129. * It will both interacts on the Geometry for analytical and IBL lighting.
  46130. * It also prefilter the roughness map based on the bump values.
  46131. */
  46132. _this.enableSpecularAntiAliasing = false;
  46133. /**
  46134. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46135. * makes the reflect vector face the model (under horizon).
  46136. */
  46137. _this.useHorizonOcclusion = true;
  46138. /**
  46139. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46140. * too much the area relying on ambient texture to define their ambient occlusion.
  46141. */
  46142. _this.useRadianceOcclusion = true;
  46143. /**
  46144. * If set to true, no lighting calculations will be applied.
  46145. */
  46146. _this.unlit = false;
  46147. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46148. return _this;
  46149. }
  46150. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46151. /**
  46152. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46153. */
  46154. get: function () {
  46155. return this._PBRMATERIAL_OPAQUE;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46161. /**
  46162. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46163. */
  46164. get: function () {
  46165. return this._PBRMATERIAL_ALPHATEST;
  46166. },
  46167. enumerable: true,
  46168. configurable: true
  46169. });
  46170. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46171. /**
  46172. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46173. */
  46174. get: function () {
  46175. return this._PBRMATERIAL_ALPHABLEND;
  46176. },
  46177. enumerable: true,
  46178. configurable: true
  46179. });
  46180. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46181. /**
  46182. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46183. * They are also discarded below the alpha cutoff threshold to improve performances.
  46184. */
  46185. get: function () {
  46186. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46187. },
  46188. enumerable: true,
  46189. configurable: true
  46190. });
  46191. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46192. /**
  46193. * Gets the image processing configuration used either in this material.
  46194. */
  46195. get: function () {
  46196. return this._imageProcessingConfiguration;
  46197. },
  46198. /**
  46199. * Sets the Default image processing configuration used either in the this material.
  46200. *
  46201. * If sets to null, the scene one is in use.
  46202. */
  46203. set: function (value) {
  46204. this._attachImageProcessingConfiguration(value);
  46205. // Ensure the effect will be rebuilt.
  46206. this._markAllSubMeshesAsTexturesDirty();
  46207. },
  46208. enumerable: true,
  46209. configurable: true
  46210. });
  46211. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46212. /**
  46213. * Gets wether the color curves effect is enabled.
  46214. */
  46215. get: function () {
  46216. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46217. },
  46218. /**
  46219. * Sets wether the color curves effect is enabled.
  46220. */
  46221. set: function (value) {
  46222. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46223. },
  46224. enumerable: true,
  46225. configurable: true
  46226. });
  46227. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46228. /**
  46229. * Gets wether the color grading effect is enabled.
  46230. */
  46231. get: function () {
  46232. return this.imageProcessingConfiguration.colorGradingEnabled;
  46233. },
  46234. /**
  46235. * Gets wether the color grading effect is enabled.
  46236. */
  46237. set: function (value) {
  46238. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46244. /**
  46245. * Gets wether tonemapping is enabled or not.
  46246. */
  46247. get: function () {
  46248. return this._imageProcessingConfiguration.toneMappingEnabled;
  46249. },
  46250. /**
  46251. * Sets wether tonemapping is enabled or not
  46252. */
  46253. set: function (value) {
  46254. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46255. },
  46256. enumerable: true,
  46257. configurable: true
  46258. });
  46259. ;
  46260. ;
  46261. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46262. /**
  46263. * The camera exposure used on this material.
  46264. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46265. * This corresponds to a photographic exposure.
  46266. */
  46267. get: function () {
  46268. return this._imageProcessingConfiguration.exposure;
  46269. },
  46270. /**
  46271. * The camera exposure used on this material.
  46272. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46273. * This corresponds to a photographic exposure.
  46274. */
  46275. set: function (value) {
  46276. this._imageProcessingConfiguration.exposure = value;
  46277. },
  46278. enumerable: true,
  46279. configurable: true
  46280. });
  46281. ;
  46282. ;
  46283. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46284. /**
  46285. * Gets The camera contrast used on this material.
  46286. */
  46287. get: function () {
  46288. return this._imageProcessingConfiguration.contrast;
  46289. },
  46290. /**
  46291. * Sets The camera contrast used on this material.
  46292. */
  46293. set: function (value) {
  46294. this._imageProcessingConfiguration.contrast = value;
  46295. },
  46296. enumerable: true,
  46297. configurable: true
  46298. });
  46299. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46300. /**
  46301. * Gets the Color Grading 2D Lookup Texture.
  46302. */
  46303. get: function () {
  46304. return this._imageProcessingConfiguration.colorGradingTexture;
  46305. },
  46306. /**
  46307. * Sets the Color Grading 2D Lookup Texture.
  46308. */
  46309. set: function (value) {
  46310. this._imageProcessingConfiguration.colorGradingTexture = value;
  46311. },
  46312. enumerable: true,
  46313. configurable: true
  46314. });
  46315. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46316. /**
  46317. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46318. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46319. * 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;
  46320. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46321. */
  46322. get: function () {
  46323. return this._imageProcessingConfiguration.colorCurves;
  46324. },
  46325. /**
  46326. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46327. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46328. * 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;
  46329. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46330. */
  46331. set: function (value) {
  46332. this._imageProcessingConfiguration.colorCurves = value;
  46333. },
  46334. enumerable: true,
  46335. configurable: true
  46336. });
  46337. /**
  46338. * Returns the name of this material class.
  46339. */
  46340. PBRMaterial.prototype.getClassName = function () {
  46341. return "PBRMaterial";
  46342. };
  46343. /**
  46344. * Returns an array of the actively used textures.
  46345. * @returns - Array of BaseTextures
  46346. */
  46347. PBRMaterial.prototype.getActiveTextures = function () {
  46348. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46349. if (this._albedoTexture) {
  46350. activeTextures.push(this._albedoTexture);
  46351. }
  46352. if (this._ambientTexture) {
  46353. activeTextures.push(this._ambientTexture);
  46354. }
  46355. if (this._opacityTexture) {
  46356. activeTextures.push(this._opacityTexture);
  46357. }
  46358. if (this._reflectionTexture) {
  46359. activeTextures.push(this._reflectionTexture);
  46360. }
  46361. if (this._emissiveTexture) {
  46362. activeTextures.push(this._emissiveTexture);
  46363. }
  46364. if (this._reflectivityTexture) {
  46365. activeTextures.push(this._reflectivityTexture);
  46366. }
  46367. if (this._metallicTexture) {
  46368. activeTextures.push(this._metallicTexture);
  46369. }
  46370. if (this._microSurfaceTexture) {
  46371. activeTextures.push(this._microSurfaceTexture);
  46372. }
  46373. if (this._bumpTexture) {
  46374. activeTextures.push(this._bumpTexture);
  46375. }
  46376. if (this._lightmapTexture) {
  46377. activeTextures.push(this._lightmapTexture);
  46378. }
  46379. if (this._refractionTexture) {
  46380. activeTextures.push(this._refractionTexture);
  46381. }
  46382. return activeTextures;
  46383. };
  46384. /**
  46385. * Checks to see if a texture is used in the material.
  46386. * @param texture - Base texture to use.
  46387. * @returns - Boolean specifying if a texture is used in the material.
  46388. */
  46389. PBRMaterial.prototype.hasTexture = function (texture) {
  46390. if (_super.prototype.hasTexture.call(this, texture)) {
  46391. return true;
  46392. }
  46393. if (this._albedoTexture === texture) {
  46394. return true;
  46395. }
  46396. if (this._ambientTexture === texture) {
  46397. return true;
  46398. }
  46399. if (this._opacityTexture === texture) {
  46400. return true;
  46401. }
  46402. if (this._reflectionTexture === texture) {
  46403. return true;
  46404. }
  46405. if (this._reflectivityTexture === texture) {
  46406. return true;
  46407. }
  46408. if (this._metallicTexture === texture) {
  46409. return true;
  46410. }
  46411. if (this._microSurfaceTexture === texture) {
  46412. return true;
  46413. }
  46414. if (this._bumpTexture === texture) {
  46415. return true;
  46416. }
  46417. if (this._lightmapTexture === texture) {
  46418. return true;
  46419. }
  46420. if (this._refractionTexture === texture) {
  46421. return true;
  46422. }
  46423. return false;
  46424. };
  46425. /**
  46426. * Makes a duplicate of the current material.
  46427. * @param name - name to use for the new material.
  46428. */
  46429. PBRMaterial.prototype.clone = function (name) {
  46430. var _this = this;
  46431. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46432. clone.id = name;
  46433. clone.name = name;
  46434. return clone;
  46435. };
  46436. /**
  46437. * Serializes this PBR Material.
  46438. * @returns - An object with the serialized material.
  46439. */
  46440. PBRMaterial.prototype.serialize = function () {
  46441. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46442. serializationObject.customType = "BABYLON.PBRMaterial";
  46443. return serializationObject;
  46444. };
  46445. // Statics
  46446. /**
  46447. * Parses a PBR Material from a serialized object.
  46448. * @param source - Serialized object.
  46449. * @param scene - BJS scene instance.
  46450. * @param rootUrl - url for the scene object
  46451. * @returns - PBRMaterial
  46452. */
  46453. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46454. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46455. };
  46456. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46457. /**
  46458. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46459. */
  46460. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46461. /**
  46462. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46463. */
  46464. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46465. /**
  46466. * 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.
  46467. * They are also discarded below the alpha cutoff threshold to improve performances.
  46468. */
  46469. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46470. __decorate([
  46471. BABYLON.serialize(),
  46472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46473. ], PBRMaterial.prototype, "directIntensity", void 0);
  46474. __decorate([
  46475. BABYLON.serialize(),
  46476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46477. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46478. __decorate([
  46479. BABYLON.serialize(),
  46480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46481. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46482. __decorate([
  46483. BABYLON.serialize(),
  46484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46485. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46486. __decorate([
  46487. BABYLON.serialize(),
  46488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46489. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46490. __decorate([
  46491. BABYLON.serializeAsTexture(),
  46492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46493. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46494. __decorate([
  46495. BABYLON.serializeAsTexture(),
  46496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46497. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46498. __decorate([
  46499. BABYLON.serialize(),
  46500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46501. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46502. __decorate([
  46503. BABYLON.serializeAsTexture(),
  46504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46505. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46506. __decorate([
  46507. BABYLON.serializeAsTexture(),
  46508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46509. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46510. __decorate([
  46511. BABYLON.serializeAsTexture(),
  46512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46513. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46514. __decorate([
  46515. BABYLON.serializeAsTexture(),
  46516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46517. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46518. __decorate([
  46519. BABYLON.serializeAsTexture(),
  46520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46521. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46522. __decorate([
  46523. BABYLON.serialize(),
  46524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46525. ], PBRMaterial.prototype, "metallic", void 0);
  46526. __decorate([
  46527. BABYLON.serialize(),
  46528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46529. ], PBRMaterial.prototype, "roughness", void 0);
  46530. __decorate([
  46531. BABYLON.serializeAsTexture(),
  46532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46533. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46534. __decorate([
  46535. BABYLON.serializeAsTexture(),
  46536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46537. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46538. __decorate([
  46539. BABYLON.serializeAsTexture(),
  46540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46541. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46542. __decorate([
  46543. BABYLON.serializeAsTexture(),
  46544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46545. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46546. __decorate([
  46547. BABYLON.serializeAsColor3("ambient"),
  46548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46549. ], PBRMaterial.prototype, "ambientColor", void 0);
  46550. __decorate([
  46551. BABYLON.serializeAsColor3("albedo"),
  46552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46553. ], PBRMaterial.prototype, "albedoColor", void 0);
  46554. __decorate([
  46555. BABYLON.serializeAsColor3("reflectivity"),
  46556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46557. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46558. __decorate([
  46559. BABYLON.serializeAsColor3("reflection"),
  46560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46561. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46562. __decorate([
  46563. BABYLON.serializeAsColor3("emissive"),
  46564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46565. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46566. __decorate([
  46567. BABYLON.serialize(),
  46568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46569. ], PBRMaterial.prototype, "microSurface", void 0);
  46570. __decorate([
  46571. BABYLON.serialize(),
  46572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46573. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46574. __decorate([
  46575. BABYLON.serialize(),
  46576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46577. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46578. __decorate([
  46579. BABYLON.serialize(),
  46580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46581. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46582. __decorate([
  46583. BABYLON.serialize(),
  46584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46585. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46586. __decorate([
  46587. BABYLON.serialize(),
  46588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46589. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46590. __decorate([
  46591. BABYLON.serialize(),
  46592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46593. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46594. __decorate([
  46595. BABYLON.serialize(),
  46596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46597. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46598. __decorate([
  46599. BABYLON.serialize(),
  46600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46601. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46602. __decorate([
  46603. BABYLON.serialize(),
  46604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46605. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46606. __decorate([
  46607. BABYLON.serialize(),
  46608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46609. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46610. __decorate([
  46611. BABYLON.serialize(),
  46612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46613. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46614. __decorate([
  46615. BABYLON.serialize(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46617. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46618. __decorate([
  46619. BABYLON.serialize(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46621. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46622. __decorate([
  46623. BABYLON.serialize(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46626. __decorate([
  46627. BABYLON.serialize(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46633. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46634. __decorate([
  46635. BABYLON.serialize(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46637. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46638. __decorate([
  46639. BABYLON.serialize(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46641. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46642. __decorate([
  46643. BABYLON.serialize(),
  46644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46645. ], PBRMaterial.prototype, "useParallax", void 0);
  46646. __decorate([
  46647. BABYLON.serialize(),
  46648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46649. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46650. __decorate([
  46651. BABYLON.serialize(),
  46652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46653. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46654. __decorate([
  46655. BABYLON.serialize(),
  46656. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46657. ], PBRMaterial.prototype, "disableLighting", void 0);
  46658. __decorate([
  46659. BABYLON.serialize(),
  46660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46661. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46662. __decorate([
  46663. BABYLON.serialize(),
  46664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46665. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46666. __decorate([
  46667. BABYLON.serialize(),
  46668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46669. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46670. __decorate([
  46671. BABYLON.serialize(),
  46672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46673. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46674. __decorate([
  46675. BABYLON.serialize(),
  46676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46677. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46678. __decorate([
  46679. BABYLON.serialize(),
  46680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46681. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46682. __decorate([
  46683. BABYLON.serialize(),
  46684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46685. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46686. __decorate([
  46687. BABYLON.serializeAsTexture(),
  46688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46689. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46690. __decorate([
  46691. BABYLON.serialize(),
  46692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46693. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46694. __decorate([
  46695. BABYLON.serialize(),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46697. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46698. __decorate([
  46699. BABYLON.serialize(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46701. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46702. __decorate([
  46703. BABYLON.serialize(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46705. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46706. __decorate([
  46707. BABYLON.serialize(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46709. ], PBRMaterial.prototype, "unlit", void 0);
  46710. return PBRMaterial;
  46711. }(BABYLON.PBRBaseMaterial));
  46712. BABYLON.PBRMaterial = PBRMaterial;
  46713. })(BABYLON || (BABYLON = {}));
  46714. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46715. var BABYLON;
  46716. (function (BABYLON) {
  46717. /**
  46718. * The PBR material of BJS following the metal roughness convention.
  46719. *
  46720. * This fits to the PBR convention in the GLTF definition:
  46721. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46722. */
  46723. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46724. __extends(PBRMetallicRoughnessMaterial, _super);
  46725. /**
  46726. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46727. *
  46728. * @param name The material name
  46729. * @param scene The scene the material will be use in.
  46730. */
  46731. function PBRMetallicRoughnessMaterial(name, scene) {
  46732. var _this = _super.call(this, name, scene) || this;
  46733. _this._useRoughnessFromMetallicTextureAlpha = false;
  46734. _this._useRoughnessFromMetallicTextureGreen = true;
  46735. _this._useMetallnessFromMetallicTextureBlue = true;
  46736. _this.metallic = 1.0;
  46737. _this.roughness = 1.0;
  46738. return _this;
  46739. }
  46740. /**
  46741. * Return the currrent class name of the material.
  46742. */
  46743. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46744. return "PBRMetallicRoughnessMaterial";
  46745. };
  46746. /**
  46747. * Return the active textures of the material.
  46748. */
  46749. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46750. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46751. if (this.baseTexture) {
  46752. activeTextures.push(this.baseTexture);
  46753. }
  46754. if (this.metallicRoughnessTexture) {
  46755. activeTextures.push(this.metallicRoughnessTexture);
  46756. }
  46757. return activeTextures;
  46758. };
  46759. /**
  46760. * Checks to see if a texture is used in the material.
  46761. * @param texture - Base texture to use.
  46762. * @returns - Boolean specifying if a texture is used in the material.
  46763. */
  46764. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46765. if (_super.prototype.hasTexture.call(this, texture)) {
  46766. return true;
  46767. }
  46768. if (this.baseTexture === texture) {
  46769. return true;
  46770. }
  46771. if (this.metallicRoughnessTexture === texture) {
  46772. return true;
  46773. }
  46774. return false;
  46775. };
  46776. /**
  46777. * Makes a duplicate of the current material.
  46778. * @param name - name to use for the new material.
  46779. */
  46780. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46781. var _this = this;
  46782. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46783. clone.id = name;
  46784. clone.name = name;
  46785. return clone;
  46786. };
  46787. /**
  46788. * Serialize the material to a parsable JSON object.
  46789. */
  46790. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46791. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46792. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46793. return serializationObject;
  46794. };
  46795. /**
  46796. * Parses a JSON object correponding to the serialize function.
  46797. */
  46798. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46799. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46800. };
  46801. __decorate([
  46802. BABYLON.serializeAsColor3(),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46804. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46805. __decorate([
  46806. BABYLON.serializeAsTexture(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46808. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46809. __decorate([
  46810. BABYLON.serialize(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46812. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46813. __decorate([
  46814. BABYLON.serialize(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46816. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46817. __decorate([
  46818. BABYLON.serializeAsTexture(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46820. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46821. return PBRMetallicRoughnessMaterial;
  46822. }(BABYLON.PBRBaseSimpleMaterial));
  46823. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46824. })(BABYLON || (BABYLON = {}));
  46825. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46826. var BABYLON;
  46827. (function (BABYLON) {
  46828. /**
  46829. * The PBR material of BJS following the specular glossiness convention.
  46830. *
  46831. * This fits to the PBR convention in the GLTF definition:
  46832. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46833. */
  46834. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46835. __extends(PBRSpecularGlossinessMaterial, _super);
  46836. /**
  46837. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46838. *
  46839. * @param name The material name
  46840. * @param scene The scene the material will be use in.
  46841. */
  46842. function PBRSpecularGlossinessMaterial(name, scene) {
  46843. var _this = _super.call(this, name, scene) || this;
  46844. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46845. return _this;
  46846. }
  46847. /**
  46848. * Return the currrent class name of the material.
  46849. */
  46850. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46851. return "PBRSpecularGlossinessMaterial";
  46852. };
  46853. /**
  46854. * Return the active textures of the material.
  46855. */
  46856. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46857. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46858. if (this.diffuseTexture) {
  46859. activeTextures.push(this.diffuseTexture);
  46860. }
  46861. if (this.specularGlossinessTexture) {
  46862. activeTextures.push(this.specularGlossinessTexture);
  46863. }
  46864. return activeTextures;
  46865. };
  46866. /**
  46867. * Checks to see if a texture is used in the material.
  46868. * @param texture - Base texture to use.
  46869. * @returns - Boolean specifying if a texture is used in the material.
  46870. */
  46871. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46872. if (_super.prototype.hasTexture.call(this, texture)) {
  46873. return true;
  46874. }
  46875. if (this.diffuseTexture === texture) {
  46876. return true;
  46877. }
  46878. if (this.specularGlossinessTexture === texture) {
  46879. return true;
  46880. }
  46881. return false;
  46882. };
  46883. /**
  46884. * Makes a duplicate of the current material.
  46885. * @param name - name to use for the new material.
  46886. */
  46887. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46888. var _this = this;
  46889. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46890. clone.id = name;
  46891. clone.name = name;
  46892. return clone;
  46893. };
  46894. /**
  46895. * Serialize the material to a parsable JSON object.
  46896. */
  46897. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46898. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46899. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46900. return serializationObject;
  46901. };
  46902. /**
  46903. * Parses a JSON object correponding to the serialize function.
  46904. */
  46905. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46906. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46907. };
  46908. __decorate([
  46909. BABYLON.serializeAsColor3("diffuse"),
  46910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46911. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46912. __decorate([
  46913. BABYLON.serializeAsTexture(),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46915. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46916. __decorate([
  46917. BABYLON.serializeAsColor3("specular"),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46919. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46920. __decorate([
  46921. BABYLON.serialize(),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46923. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46924. __decorate([
  46925. BABYLON.serializeAsTexture(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46927. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46928. return PBRSpecularGlossinessMaterial;
  46929. }(BABYLON.PBRBaseSimpleMaterial));
  46930. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46931. })(BABYLON || (BABYLON = {}));
  46932. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46933. var BABYLON;
  46934. (function (BABYLON) {
  46935. BABYLON.CameraInputTypes = {};
  46936. var CameraInputsManager = /** @class */ (function () {
  46937. function CameraInputsManager(camera) {
  46938. this.attached = {};
  46939. this.camera = camera;
  46940. this.checkInputs = function () { };
  46941. }
  46942. /**
  46943. * Add an input method to a camera.
  46944. * builtin inputs example: camera.inputs.addGamepad();
  46945. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46946. * @param input camera input method
  46947. */
  46948. CameraInputsManager.prototype.add = function (input) {
  46949. var type = input.getSimpleName();
  46950. if (this.attached[type]) {
  46951. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46952. return;
  46953. }
  46954. this.attached[type] = input;
  46955. input.camera = this.camera;
  46956. //for checkInputs, we are dynamically creating a function
  46957. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46958. if (input.checkInputs) {
  46959. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46960. }
  46961. if (this.attachedElement) {
  46962. input.attachControl(this.attachedElement);
  46963. }
  46964. };
  46965. /**
  46966. * Remove a specific input method from a camera
  46967. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46968. * @param inputToRemove camera input method
  46969. */
  46970. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46971. for (var cam in this.attached) {
  46972. var input = this.attached[cam];
  46973. if (input === inputToRemove) {
  46974. input.detachControl(this.attachedElement);
  46975. input.camera = null;
  46976. delete this.attached[cam];
  46977. this.rebuildInputCheck();
  46978. }
  46979. }
  46980. };
  46981. CameraInputsManager.prototype.removeByType = function (inputType) {
  46982. for (var cam in this.attached) {
  46983. var input = this.attached[cam];
  46984. if (input.getClassName() === inputType) {
  46985. input.detachControl(this.attachedElement);
  46986. input.camera = null;
  46987. delete this.attached[cam];
  46988. this.rebuildInputCheck();
  46989. }
  46990. }
  46991. };
  46992. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46993. var current = this.checkInputs;
  46994. return function () {
  46995. current();
  46996. fn();
  46997. };
  46998. };
  46999. CameraInputsManager.prototype.attachInput = function (input) {
  47000. if (this.attachedElement) {
  47001. input.attachControl(this.attachedElement, this.noPreventDefault);
  47002. }
  47003. };
  47004. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47005. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47006. if (this.attachedElement) {
  47007. return;
  47008. }
  47009. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47010. this.attachedElement = element;
  47011. this.noPreventDefault = noPreventDefault;
  47012. for (var cam in this.attached) {
  47013. this.attached[cam].attachControl(element, noPreventDefault);
  47014. }
  47015. };
  47016. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47017. if (disconnect === void 0) { disconnect = false; }
  47018. if (this.attachedElement !== element) {
  47019. return;
  47020. }
  47021. for (var cam in this.attached) {
  47022. this.attached[cam].detachControl(element);
  47023. if (disconnect) {
  47024. this.attached[cam].camera = null;
  47025. }
  47026. }
  47027. this.attachedElement = null;
  47028. };
  47029. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47030. this.checkInputs = function () { };
  47031. for (var cam in this.attached) {
  47032. var input = this.attached[cam];
  47033. if (input.checkInputs) {
  47034. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47035. }
  47036. }
  47037. };
  47038. /**
  47039. * Remove all attached input methods from a camera
  47040. */
  47041. CameraInputsManager.prototype.clear = function () {
  47042. if (this.attachedElement) {
  47043. this.detachElement(this.attachedElement, true);
  47044. }
  47045. this.attached = {};
  47046. this.attachedElement = null;
  47047. this.checkInputs = function () { };
  47048. };
  47049. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47050. var inputs = {};
  47051. for (var cam in this.attached) {
  47052. var input = this.attached[cam];
  47053. var res = BABYLON.SerializationHelper.Serialize(input);
  47054. inputs[input.getClassName()] = res;
  47055. }
  47056. serializedCamera.inputsmgr = inputs;
  47057. };
  47058. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47059. var parsedInputs = parsedCamera.inputsmgr;
  47060. if (parsedInputs) {
  47061. this.clear();
  47062. for (var n in parsedInputs) {
  47063. var construct = BABYLON.CameraInputTypes[n];
  47064. if (construct) {
  47065. var parsedinput = parsedInputs[n];
  47066. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47067. this.add(input);
  47068. }
  47069. }
  47070. }
  47071. else {
  47072. //2016-03-08 this part is for managing backward compatibility
  47073. for (var n in this.attached) {
  47074. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47075. if (construct) {
  47076. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47077. this.remove(this.attached[n]);
  47078. this.add(input);
  47079. }
  47080. }
  47081. }
  47082. };
  47083. return CameraInputsManager;
  47084. }());
  47085. BABYLON.CameraInputsManager = CameraInputsManager;
  47086. })(BABYLON || (BABYLON = {}));
  47087. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47088. var BABYLON;
  47089. (function (BABYLON) {
  47090. var TargetCamera = /** @class */ (function (_super) {
  47091. __extends(TargetCamera, _super);
  47092. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47093. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47094. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47095. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47096. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47097. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47098. _this.speed = 2.0;
  47099. _this.noRotationConstraint = false;
  47100. _this.lockedTarget = null;
  47101. _this._currentTarget = BABYLON.Vector3.Zero();
  47102. _this._viewMatrix = BABYLON.Matrix.Zero();
  47103. _this._camMatrix = BABYLON.Matrix.Zero();
  47104. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47105. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47106. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47107. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47108. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47109. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47110. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47111. return _this;
  47112. }
  47113. TargetCamera.prototype.getFrontPosition = function (distance) {
  47114. this.getWorldMatrix();
  47115. var direction = this.getTarget().subtract(this.position);
  47116. direction.normalize();
  47117. direction.scaleInPlace(distance);
  47118. return this.globalPosition.add(direction);
  47119. };
  47120. TargetCamera.prototype._getLockedTargetPosition = function () {
  47121. if (!this.lockedTarget) {
  47122. return null;
  47123. }
  47124. if (this.lockedTarget.absolutePosition) {
  47125. this.lockedTarget.computeWorldMatrix();
  47126. }
  47127. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47128. };
  47129. TargetCamera.prototype.storeState = function () {
  47130. this._storedPosition = this.position.clone();
  47131. this._storedRotation = this.rotation.clone();
  47132. if (this.rotationQuaternion) {
  47133. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47134. }
  47135. return _super.prototype.storeState.call(this);
  47136. };
  47137. /**
  47138. * Restored camera state. You must call storeState() first
  47139. */
  47140. TargetCamera.prototype._restoreStateValues = function () {
  47141. if (!_super.prototype._restoreStateValues.call(this)) {
  47142. return false;
  47143. }
  47144. this.position = this._storedPosition.clone();
  47145. this.rotation = this._storedRotation.clone();
  47146. if (this.rotationQuaternion) {
  47147. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47148. }
  47149. this.cameraDirection.copyFromFloats(0, 0, 0);
  47150. this.cameraRotation.copyFromFloats(0, 0);
  47151. return true;
  47152. };
  47153. // Cache
  47154. TargetCamera.prototype._initCache = function () {
  47155. _super.prototype._initCache.call(this);
  47156. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47157. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47158. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47159. };
  47160. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47161. if (!ignoreParentClass) {
  47162. _super.prototype._updateCache.call(this);
  47163. }
  47164. var lockedTargetPosition = this._getLockedTargetPosition();
  47165. if (!lockedTargetPosition) {
  47166. this._cache.lockedTarget = null;
  47167. }
  47168. else {
  47169. if (!this._cache.lockedTarget) {
  47170. this._cache.lockedTarget = lockedTargetPosition.clone();
  47171. }
  47172. else {
  47173. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47174. }
  47175. }
  47176. this._cache.rotation.copyFrom(this.rotation);
  47177. if (this.rotationQuaternion)
  47178. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47179. };
  47180. // Synchronized
  47181. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47182. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47183. return false;
  47184. }
  47185. var lockedTargetPosition = this._getLockedTargetPosition();
  47186. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47187. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47188. };
  47189. // Methods
  47190. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47191. var engine = this.getEngine();
  47192. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47193. };
  47194. // Target
  47195. TargetCamera.prototype.setTarget = function (target) {
  47196. this.upVector.normalize();
  47197. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47198. this._camMatrix.invert();
  47199. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47200. var vDir = target.subtract(this.position);
  47201. if (vDir.x >= 0.0) {
  47202. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47203. }
  47204. else {
  47205. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47206. }
  47207. this.rotation.z = 0;
  47208. if (isNaN(this.rotation.x)) {
  47209. this.rotation.x = 0;
  47210. }
  47211. if (isNaN(this.rotation.y)) {
  47212. this.rotation.y = 0;
  47213. }
  47214. if (isNaN(this.rotation.z)) {
  47215. this.rotation.z = 0;
  47216. }
  47217. if (this.rotationQuaternion) {
  47218. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47219. }
  47220. };
  47221. /**
  47222. * Return the current target position of the camera. This value is expressed in local space.
  47223. */
  47224. TargetCamera.prototype.getTarget = function () {
  47225. return this._currentTarget;
  47226. };
  47227. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47228. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47229. };
  47230. TargetCamera.prototype._updatePosition = function () {
  47231. if (this.parent) {
  47232. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47233. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47234. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47235. return;
  47236. }
  47237. this.position.addInPlace(this.cameraDirection);
  47238. };
  47239. TargetCamera.prototype._checkInputs = function () {
  47240. var needToMove = this._decideIfNeedsToMove();
  47241. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47242. // Move
  47243. if (needToMove) {
  47244. this._updatePosition();
  47245. }
  47246. // Rotate
  47247. if (needToRotate) {
  47248. this.rotation.x += this.cameraRotation.x;
  47249. this.rotation.y += this.cameraRotation.y;
  47250. //rotate, if quaternion is set and rotation was used
  47251. if (this.rotationQuaternion) {
  47252. var len = this.rotation.lengthSquared();
  47253. if (len) {
  47254. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47255. }
  47256. }
  47257. if (!this.noRotationConstraint) {
  47258. var limit = (Math.PI / 2) * 0.95;
  47259. if (this.rotation.x > limit)
  47260. this.rotation.x = limit;
  47261. if (this.rotation.x < -limit)
  47262. this.rotation.x = -limit;
  47263. }
  47264. }
  47265. // Inertia
  47266. if (needToMove) {
  47267. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47268. this.cameraDirection.x = 0;
  47269. }
  47270. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47271. this.cameraDirection.y = 0;
  47272. }
  47273. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47274. this.cameraDirection.z = 0;
  47275. }
  47276. this.cameraDirection.scaleInPlace(this.inertia);
  47277. }
  47278. if (needToRotate) {
  47279. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47280. this.cameraRotation.x = 0;
  47281. }
  47282. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47283. this.cameraRotation.y = 0;
  47284. }
  47285. this.cameraRotation.scaleInPlace(this.inertia);
  47286. }
  47287. _super.prototype._checkInputs.call(this);
  47288. };
  47289. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47290. if (this.rotationQuaternion) {
  47291. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47292. }
  47293. else {
  47294. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47295. }
  47296. //update the up vector!
  47297. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47298. };
  47299. TargetCamera.prototype._getViewMatrix = function () {
  47300. if (this.lockedTarget) {
  47301. this.setTarget(this._getLockedTargetPosition());
  47302. }
  47303. // Compute
  47304. this._updateCameraRotationMatrix();
  47305. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47306. // Computing target and final matrix
  47307. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47308. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47309. return this._viewMatrix;
  47310. };
  47311. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47312. if (this.parent) {
  47313. var parentWorldMatrix = this.parent.getWorldMatrix();
  47314. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47315. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47316. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47317. this._markSyncedWithParent();
  47318. }
  47319. else {
  47320. this._globalPosition.copyFrom(this.position);
  47321. this._globalCurrentTarget.copyFrom(target);
  47322. this._globalCurrentUpVector.copyFrom(up);
  47323. }
  47324. if (this.getScene().useRightHandedSystem) {
  47325. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47326. }
  47327. else {
  47328. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47329. }
  47330. };
  47331. /**
  47332. * @override
  47333. * Override Camera.createRigCamera
  47334. */
  47335. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47336. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47337. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47338. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47339. if (!this.rotationQuaternion) {
  47340. this.rotationQuaternion = new BABYLON.Quaternion();
  47341. }
  47342. rigCamera._cameraRigParams = {};
  47343. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47344. }
  47345. return rigCamera;
  47346. }
  47347. return null;
  47348. };
  47349. /**
  47350. * @override
  47351. * Override Camera._updateRigCameras
  47352. */
  47353. TargetCamera.prototype._updateRigCameras = function () {
  47354. var camLeft = this._rigCameras[0];
  47355. var camRight = this._rigCameras[1];
  47356. switch (this.cameraRigMode) {
  47357. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47358. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47359. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47360. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47361. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47362. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47363. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47364. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47365. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47366. camLeft.setTarget(this.getTarget());
  47367. camRight.setTarget(this.getTarget());
  47368. break;
  47369. case BABYLON.Camera.RIG_MODE_VR:
  47370. if (camLeft.rotationQuaternion) {
  47371. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47372. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47373. }
  47374. else {
  47375. camLeft.rotation.copyFrom(this.rotation);
  47376. camRight.rotation.copyFrom(this.rotation);
  47377. }
  47378. camLeft.position.copyFrom(this.position);
  47379. camRight.position.copyFrom(this.position);
  47380. break;
  47381. }
  47382. _super.prototype._updateRigCameras.call(this);
  47383. };
  47384. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47385. if (!this._rigCamTransformMatrix) {
  47386. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47387. }
  47388. var target = this.getTarget();
  47389. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47390. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47391. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47392. };
  47393. TargetCamera.prototype.getClassName = function () {
  47394. return "TargetCamera";
  47395. };
  47396. __decorate([
  47397. BABYLON.serializeAsVector3()
  47398. ], TargetCamera.prototype, "rotation", void 0);
  47399. __decorate([
  47400. BABYLON.serialize()
  47401. ], TargetCamera.prototype, "speed", void 0);
  47402. __decorate([
  47403. BABYLON.serializeAsMeshReference("lockedTargetId")
  47404. ], TargetCamera.prototype, "lockedTarget", void 0);
  47405. return TargetCamera;
  47406. }(BABYLON.Camera));
  47407. BABYLON.TargetCamera = TargetCamera;
  47408. })(BABYLON || (BABYLON = {}));
  47409. //# sourceMappingURL=babylon.targetCamera.js.map
  47410. var BABYLON;
  47411. (function (BABYLON) {
  47412. var FreeCameraMouseInput = /** @class */ (function () {
  47413. function FreeCameraMouseInput(touchEnabled) {
  47414. if (touchEnabled === void 0) { touchEnabled = true; }
  47415. this.touchEnabled = touchEnabled;
  47416. this.buttons = [0, 1, 2];
  47417. this.angularSensibility = 2000.0;
  47418. this.previousPosition = null;
  47419. }
  47420. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47421. var _this = this;
  47422. var engine = this.camera.getEngine();
  47423. if (!this._pointerInput) {
  47424. this._pointerInput = function (p, s) {
  47425. var evt = p.event;
  47426. if (engine.isInVRExclusivePointerMode) {
  47427. return;
  47428. }
  47429. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47430. return;
  47431. }
  47432. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47433. return;
  47434. }
  47435. var srcElement = (evt.srcElement || evt.target);
  47436. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47437. try {
  47438. srcElement.setPointerCapture(evt.pointerId);
  47439. }
  47440. catch (e) {
  47441. //Nothing to do with the error. Execution will continue.
  47442. }
  47443. _this.previousPosition = {
  47444. x: evt.clientX,
  47445. y: evt.clientY
  47446. };
  47447. if (!noPreventDefault) {
  47448. evt.preventDefault();
  47449. element.focus();
  47450. }
  47451. }
  47452. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47453. try {
  47454. srcElement.releasePointerCapture(evt.pointerId);
  47455. }
  47456. catch (e) {
  47457. //Nothing to do with the error.
  47458. }
  47459. _this.previousPosition = null;
  47460. if (!noPreventDefault) {
  47461. evt.preventDefault();
  47462. }
  47463. }
  47464. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47465. if (!_this.previousPosition || engine.isPointerLock) {
  47466. return;
  47467. }
  47468. var offsetX = evt.clientX - _this.previousPosition.x;
  47469. if (_this.camera.getScene().useRightHandedSystem)
  47470. offsetX *= -1;
  47471. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47472. offsetX *= -1;
  47473. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47474. var offsetY = evt.clientY - _this.previousPosition.y;
  47475. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47476. _this.previousPosition = {
  47477. x: evt.clientX,
  47478. y: evt.clientY
  47479. };
  47480. if (!noPreventDefault) {
  47481. evt.preventDefault();
  47482. }
  47483. }
  47484. };
  47485. }
  47486. this._onMouseMove = function (evt) {
  47487. if (!engine.isPointerLock) {
  47488. return;
  47489. }
  47490. if (engine.isInVRExclusivePointerMode) {
  47491. return;
  47492. }
  47493. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47494. if (_this.camera.getScene().useRightHandedSystem)
  47495. offsetX *= -1;
  47496. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47497. offsetX *= -1;
  47498. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47499. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47500. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47501. _this.previousPosition = null;
  47502. if (!noPreventDefault) {
  47503. evt.preventDefault();
  47504. }
  47505. };
  47506. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47507. element.addEventListener("mousemove", this._onMouseMove, false);
  47508. };
  47509. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47510. if (this._observer && element) {
  47511. this.camera.getScene().onPointerObservable.remove(this._observer);
  47512. if (this._onMouseMove) {
  47513. element.removeEventListener("mousemove", this._onMouseMove);
  47514. }
  47515. this._observer = null;
  47516. this._onMouseMove = null;
  47517. this.previousPosition = null;
  47518. }
  47519. };
  47520. FreeCameraMouseInput.prototype.getClassName = function () {
  47521. return "FreeCameraMouseInput";
  47522. };
  47523. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47524. return "mouse";
  47525. };
  47526. __decorate([
  47527. BABYLON.serialize()
  47528. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47529. __decorate([
  47530. BABYLON.serialize()
  47531. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47532. return FreeCameraMouseInput;
  47533. }());
  47534. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47535. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47536. })(BABYLON || (BABYLON = {}));
  47537. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47538. var BABYLON;
  47539. (function (BABYLON) {
  47540. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47541. function FreeCameraKeyboardMoveInput() {
  47542. this._keys = new Array();
  47543. this.keysUp = [38];
  47544. this.keysDown = [40];
  47545. this.keysLeft = [37];
  47546. this.keysRight = [39];
  47547. }
  47548. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47549. var _this = this;
  47550. if (this._onCanvasBlurObserver) {
  47551. return;
  47552. }
  47553. this._scene = this.camera.getScene();
  47554. this._engine = this._scene.getEngine();
  47555. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47556. _this._keys = [];
  47557. });
  47558. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47559. var evt = info.event;
  47560. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47561. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47562. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47563. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47564. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47565. var index = _this._keys.indexOf(evt.keyCode);
  47566. if (index === -1) {
  47567. _this._keys.push(evt.keyCode);
  47568. }
  47569. if (!noPreventDefault) {
  47570. evt.preventDefault();
  47571. }
  47572. }
  47573. }
  47574. else {
  47575. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47576. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47577. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47578. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47579. var index = _this._keys.indexOf(evt.keyCode);
  47580. if (index >= 0) {
  47581. _this._keys.splice(index, 1);
  47582. }
  47583. if (!noPreventDefault) {
  47584. evt.preventDefault();
  47585. }
  47586. }
  47587. }
  47588. });
  47589. };
  47590. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47591. if (this._scene) {
  47592. if (this._onKeyboardObserver) {
  47593. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47594. }
  47595. if (this._onCanvasBlurObserver) {
  47596. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47597. }
  47598. this._onKeyboardObserver = null;
  47599. this._onCanvasBlurObserver = null;
  47600. }
  47601. this._keys = [];
  47602. };
  47603. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47604. if (this._onKeyboardObserver) {
  47605. var camera = this.camera;
  47606. // Keyboard
  47607. for (var index = 0; index < this._keys.length; index++) {
  47608. var keyCode = this._keys[index];
  47609. var speed = camera._computeLocalCameraSpeed();
  47610. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47611. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47612. }
  47613. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47614. camera._localDirection.copyFromFloats(0, 0, speed);
  47615. }
  47616. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47617. camera._localDirection.copyFromFloats(speed, 0, 0);
  47618. }
  47619. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47620. camera._localDirection.copyFromFloats(0, 0, -speed);
  47621. }
  47622. if (camera.getScene().useRightHandedSystem) {
  47623. camera._localDirection.z *= -1;
  47624. }
  47625. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47626. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47627. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47628. }
  47629. }
  47630. };
  47631. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47632. return "FreeCameraKeyboardMoveInput";
  47633. };
  47634. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47635. this._keys = [];
  47636. };
  47637. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47638. return "keyboard";
  47639. };
  47640. __decorate([
  47641. BABYLON.serialize()
  47642. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47643. __decorate([
  47644. BABYLON.serialize()
  47645. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47646. __decorate([
  47647. BABYLON.serialize()
  47648. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47649. __decorate([
  47650. BABYLON.serialize()
  47651. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47652. return FreeCameraKeyboardMoveInput;
  47653. }());
  47654. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47655. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47656. })(BABYLON || (BABYLON = {}));
  47657. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47658. var BABYLON;
  47659. (function (BABYLON) {
  47660. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47661. __extends(FreeCameraInputsManager, _super);
  47662. function FreeCameraInputsManager(camera) {
  47663. return _super.call(this, camera) || this;
  47664. }
  47665. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47666. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47667. return this;
  47668. };
  47669. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47670. if (touchEnabled === void 0) { touchEnabled = true; }
  47671. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47672. return this;
  47673. };
  47674. FreeCameraInputsManager.prototype.addGamepad = function () {
  47675. this.add(new BABYLON.FreeCameraGamepadInput());
  47676. return this;
  47677. };
  47678. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47679. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47680. return this;
  47681. };
  47682. FreeCameraInputsManager.prototype.addTouch = function () {
  47683. this.add(new BABYLON.FreeCameraTouchInput());
  47684. return this;
  47685. };
  47686. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47687. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47688. return this;
  47689. };
  47690. return FreeCameraInputsManager;
  47691. }(BABYLON.CameraInputsManager));
  47692. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47693. })(BABYLON || (BABYLON = {}));
  47694. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47695. var BABYLON;
  47696. (function (BABYLON) {
  47697. var FreeCamera = /** @class */ (function (_super) {
  47698. __extends(FreeCamera, _super);
  47699. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47700. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47701. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47702. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47703. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47704. _this.checkCollisions = false;
  47705. _this.applyGravity = false;
  47706. _this._needMoveForGravity = false;
  47707. _this._oldPosition = BABYLON.Vector3.Zero();
  47708. _this._diffPosition = BABYLON.Vector3.Zero();
  47709. _this._newPosition = BABYLON.Vector3.Zero();
  47710. // Collisions
  47711. _this._collisionMask = -1;
  47712. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47713. if (collidedMesh === void 0) { collidedMesh = null; }
  47714. //TODO move this to the collision coordinator!
  47715. if (_this.getScene().workerCollisions)
  47716. newPosition.multiplyInPlace(_this._collider._radius);
  47717. var updatePosition = function (newPos) {
  47718. _this._newPosition.copyFrom(newPos);
  47719. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47720. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47721. _this.position.addInPlace(_this._diffPosition);
  47722. if (_this.onCollide && collidedMesh) {
  47723. _this.onCollide(collidedMesh);
  47724. }
  47725. }
  47726. };
  47727. updatePosition(newPosition);
  47728. };
  47729. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47730. _this.inputs.addKeyboard().addMouse();
  47731. return _this;
  47732. }
  47733. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47734. //-- begin properties for backward compatibility for inputs
  47735. /**
  47736. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47737. * Higher values reduce sensitivity.
  47738. */
  47739. get: function () {
  47740. var mouse = this.inputs.attached["mouse"];
  47741. if (mouse)
  47742. return mouse.angularSensibility;
  47743. return 0;
  47744. },
  47745. /**
  47746. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47747. * Higher values reduce sensitivity.
  47748. */
  47749. set: function (value) {
  47750. var mouse = this.inputs.attached["mouse"];
  47751. if (mouse)
  47752. mouse.angularSensibility = value;
  47753. },
  47754. enumerable: true,
  47755. configurable: true
  47756. });
  47757. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47758. get: function () {
  47759. var keyboard = this.inputs.attached["keyboard"];
  47760. if (keyboard)
  47761. return keyboard.keysUp;
  47762. return [];
  47763. },
  47764. set: function (value) {
  47765. var keyboard = this.inputs.attached["keyboard"];
  47766. if (keyboard)
  47767. keyboard.keysUp = value;
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47773. get: function () {
  47774. var keyboard = this.inputs.attached["keyboard"];
  47775. if (keyboard)
  47776. return keyboard.keysDown;
  47777. return [];
  47778. },
  47779. set: function (value) {
  47780. var keyboard = this.inputs.attached["keyboard"];
  47781. if (keyboard)
  47782. keyboard.keysDown = value;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47788. get: function () {
  47789. var keyboard = this.inputs.attached["keyboard"];
  47790. if (keyboard)
  47791. return keyboard.keysLeft;
  47792. return [];
  47793. },
  47794. set: function (value) {
  47795. var keyboard = this.inputs.attached["keyboard"];
  47796. if (keyboard)
  47797. keyboard.keysLeft = value;
  47798. },
  47799. enumerable: true,
  47800. configurable: true
  47801. });
  47802. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47803. get: function () {
  47804. var keyboard = this.inputs.attached["keyboard"];
  47805. if (keyboard)
  47806. return keyboard.keysRight;
  47807. return [];
  47808. },
  47809. set: function (value) {
  47810. var keyboard = this.inputs.attached["keyboard"];
  47811. if (keyboard)
  47812. keyboard.keysRight = value;
  47813. },
  47814. enumerable: true,
  47815. configurable: true
  47816. });
  47817. // Controls
  47818. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47819. this.inputs.attachElement(element, noPreventDefault);
  47820. };
  47821. FreeCamera.prototype.detachControl = function (element) {
  47822. this.inputs.detachElement(element);
  47823. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47824. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47825. };
  47826. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47827. get: function () {
  47828. return this._collisionMask;
  47829. },
  47830. set: function (mask) {
  47831. this._collisionMask = !isNaN(mask) ? mask : -1;
  47832. },
  47833. enumerable: true,
  47834. configurable: true
  47835. });
  47836. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47837. var globalPosition;
  47838. if (this.parent) {
  47839. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47840. }
  47841. else {
  47842. globalPosition = this.position;
  47843. }
  47844. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47845. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47846. if (!this._collider) {
  47847. this._collider = new BABYLON.Collider();
  47848. }
  47849. this._collider._radius = this.ellipsoid;
  47850. this._collider.collisionMask = this._collisionMask;
  47851. //no need for clone, as long as gravity is not on.
  47852. var actualDisplacement = displacement;
  47853. //add gravity to the direction to prevent the dual-collision checking
  47854. if (this.applyGravity) {
  47855. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47856. actualDisplacement = displacement.add(this.getScene().gravity);
  47857. }
  47858. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47859. };
  47860. FreeCamera.prototype._checkInputs = function () {
  47861. if (!this._localDirection) {
  47862. this._localDirection = BABYLON.Vector3.Zero();
  47863. this._transformedDirection = BABYLON.Vector3.Zero();
  47864. }
  47865. this.inputs.checkInputs();
  47866. _super.prototype._checkInputs.call(this);
  47867. };
  47868. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47869. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47870. };
  47871. FreeCamera.prototype._updatePosition = function () {
  47872. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47873. this._collideWithWorld(this.cameraDirection);
  47874. }
  47875. else {
  47876. _super.prototype._updatePosition.call(this);
  47877. }
  47878. };
  47879. FreeCamera.prototype.dispose = function () {
  47880. this.inputs.clear();
  47881. _super.prototype.dispose.call(this);
  47882. };
  47883. FreeCamera.prototype.getClassName = function () {
  47884. return "FreeCamera";
  47885. };
  47886. __decorate([
  47887. BABYLON.serializeAsVector3()
  47888. ], FreeCamera.prototype, "ellipsoid", void 0);
  47889. __decorate([
  47890. BABYLON.serializeAsVector3()
  47891. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47892. __decorate([
  47893. BABYLON.serialize()
  47894. ], FreeCamera.prototype, "checkCollisions", void 0);
  47895. __decorate([
  47896. BABYLON.serialize()
  47897. ], FreeCamera.prototype, "applyGravity", void 0);
  47898. return FreeCamera;
  47899. }(BABYLON.TargetCamera));
  47900. BABYLON.FreeCamera = FreeCamera;
  47901. })(BABYLON || (BABYLON = {}));
  47902. //# sourceMappingURL=babylon.freeCamera.js.map
  47903. var BABYLON;
  47904. (function (BABYLON) {
  47905. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47906. function ArcRotateCameraKeyboardMoveInput() {
  47907. this._keys = new Array();
  47908. this.keysUp = [38];
  47909. this.keysDown = [40];
  47910. this.keysLeft = [37];
  47911. this.keysRight = [39];
  47912. this.keysReset = [220];
  47913. this.panningSensibility = 50.0;
  47914. this.zoomingSensibility = 25.0;
  47915. this.useAltToZoom = true;
  47916. }
  47917. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47918. var _this = this;
  47919. if (this._onCanvasBlurObserver) {
  47920. return;
  47921. }
  47922. this._scene = this.camera.getScene();
  47923. this._engine = this._scene.getEngine();
  47924. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47925. _this._keys = [];
  47926. });
  47927. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47928. var evt = info.event;
  47929. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47930. _this._ctrlPressed = evt.ctrlKey;
  47931. _this._altPressed = evt.altKey;
  47932. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47933. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47934. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47935. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47936. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47937. var index = _this._keys.indexOf(evt.keyCode);
  47938. if (index === -1) {
  47939. _this._keys.push(evt.keyCode);
  47940. }
  47941. if (evt.preventDefault) {
  47942. if (!noPreventDefault) {
  47943. evt.preventDefault();
  47944. }
  47945. }
  47946. }
  47947. }
  47948. else {
  47949. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47950. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47951. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47952. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47953. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47954. var index = _this._keys.indexOf(evt.keyCode);
  47955. if (index >= 0) {
  47956. _this._keys.splice(index, 1);
  47957. }
  47958. if (evt.preventDefault) {
  47959. if (!noPreventDefault) {
  47960. evt.preventDefault();
  47961. }
  47962. }
  47963. }
  47964. }
  47965. });
  47966. };
  47967. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47968. if (this._scene) {
  47969. if (this._onKeyboardObserver) {
  47970. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47971. }
  47972. if (this._onCanvasBlurObserver) {
  47973. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47974. }
  47975. this._onKeyboardObserver = null;
  47976. this._onCanvasBlurObserver = null;
  47977. }
  47978. this._keys = [];
  47979. };
  47980. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47981. if (this._onKeyboardObserver) {
  47982. var camera = this.camera;
  47983. for (var index = 0; index < this._keys.length; index++) {
  47984. var keyCode = this._keys[index];
  47985. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47986. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47987. camera.inertialPanningX -= 1 / this.panningSensibility;
  47988. }
  47989. else {
  47990. camera.inertialAlphaOffset -= 0.01;
  47991. }
  47992. }
  47993. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47994. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47995. camera.inertialPanningY += 1 / this.panningSensibility;
  47996. }
  47997. else if (this._altPressed && this.useAltToZoom) {
  47998. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47999. }
  48000. else {
  48001. camera.inertialBetaOffset -= 0.01;
  48002. }
  48003. }
  48004. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48005. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48006. camera.inertialPanningX += 1 / this.panningSensibility;
  48007. }
  48008. else {
  48009. camera.inertialAlphaOffset += 0.01;
  48010. }
  48011. }
  48012. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48013. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48014. camera.inertialPanningY -= 1 / this.panningSensibility;
  48015. }
  48016. else if (this._altPressed && this.useAltToZoom) {
  48017. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48018. }
  48019. else {
  48020. camera.inertialBetaOffset += 0.01;
  48021. }
  48022. }
  48023. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48024. camera.restoreState();
  48025. }
  48026. }
  48027. }
  48028. };
  48029. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48030. return "ArcRotateCameraKeyboardMoveInput";
  48031. };
  48032. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48033. return "keyboard";
  48034. };
  48035. __decorate([
  48036. BABYLON.serialize()
  48037. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48038. __decorate([
  48039. BABYLON.serialize()
  48040. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48041. __decorate([
  48042. BABYLON.serialize()
  48043. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48044. __decorate([
  48045. BABYLON.serialize()
  48046. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48047. __decorate([
  48048. BABYLON.serialize()
  48049. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48050. __decorate([
  48051. BABYLON.serialize()
  48052. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48053. __decorate([
  48054. BABYLON.serialize()
  48055. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48056. __decorate([
  48057. BABYLON.serialize()
  48058. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48059. return ArcRotateCameraKeyboardMoveInput;
  48060. }());
  48061. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48062. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48063. })(BABYLON || (BABYLON = {}));
  48064. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48065. var BABYLON;
  48066. (function (BABYLON) {
  48067. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48068. function ArcRotateCameraMouseWheelInput() {
  48069. this.wheelPrecision = 3.0;
  48070. /**
  48071. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48072. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48073. */
  48074. this.wheelDeltaPercentage = 0;
  48075. }
  48076. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48077. var _this = this;
  48078. this._wheel = function (p, s) {
  48079. //sanity check - this should be a PointerWheel event.
  48080. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48081. return;
  48082. var event = p.event;
  48083. var delta = 0;
  48084. if (event.wheelDelta) {
  48085. if (_this.wheelDeltaPercentage) {
  48086. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48087. if (event.wheelDelta > 0) {
  48088. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48089. }
  48090. else {
  48091. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48092. }
  48093. }
  48094. else {
  48095. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48096. }
  48097. }
  48098. else if (event.detail) {
  48099. delta = -event.detail / _this.wheelPrecision;
  48100. }
  48101. if (delta)
  48102. _this.camera.inertialRadiusOffset += delta;
  48103. if (event.preventDefault) {
  48104. if (!noPreventDefault) {
  48105. event.preventDefault();
  48106. }
  48107. }
  48108. };
  48109. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48110. };
  48111. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48112. if (this._observer && element) {
  48113. this.camera.getScene().onPointerObservable.remove(this._observer);
  48114. this._observer = null;
  48115. this._wheel = null;
  48116. }
  48117. };
  48118. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48119. return "ArcRotateCameraMouseWheelInput";
  48120. };
  48121. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48122. return "mousewheel";
  48123. };
  48124. __decorate([
  48125. BABYLON.serialize()
  48126. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48127. __decorate([
  48128. BABYLON.serialize()
  48129. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48130. return ArcRotateCameraMouseWheelInput;
  48131. }());
  48132. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48133. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48134. })(BABYLON || (BABYLON = {}));
  48135. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48136. var BABYLON;
  48137. (function (BABYLON) {
  48138. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48139. function ArcRotateCameraPointersInput() {
  48140. this.buttons = [0, 1, 2];
  48141. this.angularSensibilityX = 1000.0;
  48142. this.angularSensibilityY = 1000.0;
  48143. this.pinchPrecision = 12.0;
  48144. /**
  48145. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48146. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48147. */
  48148. this.pinchDeltaPercentage = 0;
  48149. this.panningSensibility = 1000.0;
  48150. this.multiTouchPanning = true;
  48151. this.multiTouchPanAndZoom = true;
  48152. this._isPanClick = false;
  48153. this.pinchInwards = true;
  48154. }
  48155. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48156. var _this = this;
  48157. var engine = this.camera.getEngine();
  48158. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48159. var pointA = null;
  48160. var pointB = null;
  48161. var previousPinchSquaredDistance = 0;
  48162. var initialDistance = 0;
  48163. var twoFingerActivityCount = 0;
  48164. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48165. this._pointerInput = function (p, s) {
  48166. var evt = p.event;
  48167. var isTouch = p.event.pointerType === "touch";
  48168. if (engine.isInVRExclusivePointerMode) {
  48169. return;
  48170. }
  48171. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48172. return;
  48173. }
  48174. var srcElement = (evt.srcElement || evt.target);
  48175. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48176. try {
  48177. srcElement.setPointerCapture(evt.pointerId);
  48178. }
  48179. catch (e) {
  48180. //Nothing to do with the error. Execution will continue.
  48181. }
  48182. // Manage panning with pan button click
  48183. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48184. // manage pointers
  48185. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48186. if (pointA === null) {
  48187. pointA = cacheSoloPointer;
  48188. }
  48189. else if (pointB === null) {
  48190. pointB = cacheSoloPointer;
  48191. }
  48192. if (!noPreventDefault) {
  48193. evt.preventDefault();
  48194. element.focus();
  48195. }
  48196. }
  48197. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48198. _this.camera.restoreState();
  48199. }
  48200. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48201. try {
  48202. srcElement.releasePointerCapture(evt.pointerId);
  48203. }
  48204. catch (e) {
  48205. //Nothing to do with the error.
  48206. }
  48207. cacheSoloPointer = null;
  48208. previousPinchSquaredDistance = 0;
  48209. previousMultiTouchPanPosition.isPaning = false;
  48210. previousMultiTouchPanPosition.isPinching = false;
  48211. twoFingerActivityCount = 0;
  48212. initialDistance = 0;
  48213. if (!isTouch) {
  48214. pointB = null; // Mouse and pen are mono pointer
  48215. }
  48216. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48217. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48218. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48219. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48220. if (engine._badOS) {
  48221. pointA = pointB = null;
  48222. }
  48223. else {
  48224. //only remove the impacted pointer in case of multitouch allowing on most
  48225. //platforms switching from rotate to zoom and pan seamlessly.
  48226. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48227. pointA = pointB;
  48228. pointB = null;
  48229. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48230. }
  48231. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48232. pointB = null;
  48233. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48234. }
  48235. else {
  48236. pointA = pointB = null;
  48237. }
  48238. }
  48239. if (!noPreventDefault) {
  48240. evt.preventDefault();
  48241. }
  48242. }
  48243. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48244. if (!noPreventDefault) {
  48245. evt.preventDefault();
  48246. }
  48247. // One button down
  48248. if (pointA && pointB === null && cacheSoloPointer) {
  48249. if (_this.panningSensibility !== 0 &&
  48250. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48251. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48252. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48253. }
  48254. else {
  48255. var offsetX = evt.clientX - cacheSoloPointer.x;
  48256. var offsetY = evt.clientY - cacheSoloPointer.y;
  48257. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48258. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48259. }
  48260. cacheSoloPointer.x = evt.clientX;
  48261. cacheSoloPointer.y = evt.clientY;
  48262. }
  48263. // Two buttons down: pinch/pan
  48264. else if (pointA && pointB) {
  48265. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48266. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48267. ed.x = evt.clientX;
  48268. ed.y = evt.clientY;
  48269. var direction = _this.pinchInwards ? 1 : -1;
  48270. var distX = pointA.x - pointB.x;
  48271. var distY = pointA.y - pointB.y;
  48272. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48273. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48274. if (previousPinchSquaredDistance === 0) {
  48275. initialDistance = pinchDistance;
  48276. previousPinchSquaredDistance = pinchSquaredDistance;
  48277. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48278. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48279. return;
  48280. }
  48281. if (_this.multiTouchPanAndZoom) {
  48282. if (_this.pinchDeltaPercentage) {
  48283. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48284. }
  48285. else {
  48286. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48287. (_this.pinchPrecision *
  48288. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48289. direction);
  48290. }
  48291. if (_this.panningSensibility !== 0) {
  48292. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48293. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48294. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48295. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48296. previousMultiTouchPanPosition.x = pointersCenterX;
  48297. previousMultiTouchPanPosition.y = pointersCenterY;
  48298. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48299. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48300. }
  48301. }
  48302. else {
  48303. twoFingerActivityCount++;
  48304. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48305. if (_this.pinchDeltaPercentage) {
  48306. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48307. }
  48308. else {
  48309. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48310. (_this.pinchPrecision *
  48311. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48312. direction);
  48313. }
  48314. previousMultiTouchPanPosition.isPaning = false;
  48315. previousMultiTouchPanPosition.isPinching = true;
  48316. }
  48317. else {
  48318. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48319. if (!previousMultiTouchPanPosition.isPaning) {
  48320. previousMultiTouchPanPosition.isPaning = true;
  48321. previousMultiTouchPanPosition.isPinching = false;
  48322. previousMultiTouchPanPosition.x = ed.x;
  48323. previousMultiTouchPanPosition.y = ed.y;
  48324. return;
  48325. }
  48326. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48327. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48328. }
  48329. }
  48330. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48331. previousMultiTouchPanPosition.x = ed.x;
  48332. previousMultiTouchPanPosition.y = ed.y;
  48333. }
  48334. }
  48335. previousPinchSquaredDistance = pinchSquaredDistance;
  48336. }
  48337. }
  48338. };
  48339. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48340. this._onContextMenu = function (evt) {
  48341. evt.preventDefault();
  48342. };
  48343. if (!this.camera._useCtrlForPanning) {
  48344. element.addEventListener("contextmenu", this._onContextMenu, false);
  48345. }
  48346. this._onLostFocus = function () {
  48347. //this._keys = [];
  48348. pointA = pointB = null;
  48349. previousPinchSquaredDistance = 0;
  48350. previousMultiTouchPanPosition.isPaning = false;
  48351. previousMultiTouchPanPosition.isPinching = false;
  48352. twoFingerActivityCount = 0;
  48353. cacheSoloPointer = null;
  48354. initialDistance = 0;
  48355. };
  48356. this._onMouseMove = function (evt) {
  48357. if (!engine.isPointerLock) {
  48358. return;
  48359. }
  48360. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48361. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48362. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48363. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48364. if (!noPreventDefault) {
  48365. evt.preventDefault();
  48366. }
  48367. };
  48368. this._onGestureStart = function (e) {
  48369. if (window.MSGesture === undefined) {
  48370. return;
  48371. }
  48372. if (!_this._MSGestureHandler) {
  48373. _this._MSGestureHandler = new MSGesture();
  48374. _this._MSGestureHandler.target = element;
  48375. }
  48376. _this._MSGestureHandler.addPointer(e.pointerId);
  48377. };
  48378. this._onGesture = function (e) {
  48379. _this.camera.radius *= e.scale;
  48380. if (e.preventDefault) {
  48381. if (!noPreventDefault) {
  48382. e.stopPropagation();
  48383. e.preventDefault();
  48384. }
  48385. }
  48386. };
  48387. element.addEventListener("mousemove", this._onMouseMove, false);
  48388. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48389. element.addEventListener("MSGestureChange", this._onGesture, false);
  48390. BABYLON.Tools.RegisterTopRootEvents([
  48391. { name: "blur", handler: this._onLostFocus }
  48392. ]);
  48393. };
  48394. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48395. if (this._onLostFocus) {
  48396. BABYLON.Tools.UnregisterTopRootEvents([
  48397. { name: "blur", handler: this._onLostFocus }
  48398. ]);
  48399. }
  48400. if (element && this._observer) {
  48401. this.camera.getScene().onPointerObservable.remove(this._observer);
  48402. this._observer = null;
  48403. if (this._onContextMenu) {
  48404. element.removeEventListener("contextmenu", this._onContextMenu);
  48405. }
  48406. if (this._onMouseMove) {
  48407. element.removeEventListener("mousemove", this._onMouseMove);
  48408. }
  48409. if (this._onGestureStart) {
  48410. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48411. }
  48412. if (this._onGesture) {
  48413. element.removeEventListener("MSGestureChange", this._onGesture);
  48414. }
  48415. this._isPanClick = false;
  48416. this.pinchInwards = true;
  48417. this._onMouseMove = null;
  48418. this._onGestureStart = null;
  48419. this._onGesture = null;
  48420. this._MSGestureHandler = null;
  48421. this._onLostFocus = null;
  48422. this._onContextMenu = null;
  48423. }
  48424. };
  48425. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48426. return "ArcRotateCameraPointersInput";
  48427. };
  48428. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48429. return "pointers";
  48430. };
  48431. __decorate([
  48432. BABYLON.serialize()
  48433. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48434. __decorate([
  48435. BABYLON.serialize()
  48436. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48437. __decorate([
  48438. BABYLON.serialize()
  48439. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48440. __decorate([
  48441. BABYLON.serialize()
  48442. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48443. __decorate([
  48444. BABYLON.serialize()
  48445. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48446. __decorate([
  48447. BABYLON.serialize()
  48448. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48449. __decorate([
  48450. BABYLON.serialize()
  48451. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48452. __decorate([
  48453. BABYLON.serialize()
  48454. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48455. return ArcRotateCameraPointersInput;
  48456. }());
  48457. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48458. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48459. })(BABYLON || (BABYLON = {}));
  48460. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48461. var BABYLON;
  48462. (function (BABYLON) {
  48463. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48464. __extends(ArcRotateCameraInputsManager, _super);
  48465. function ArcRotateCameraInputsManager(camera) {
  48466. return _super.call(this, camera) || this;
  48467. }
  48468. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48469. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48470. return this;
  48471. };
  48472. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48473. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48474. return this;
  48475. };
  48476. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48477. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48478. return this;
  48479. };
  48480. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48481. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48482. return this;
  48483. };
  48484. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48485. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48486. return this;
  48487. };
  48488. return ArcRotateCameraInputsManager;
  48489. }(BABYLON.CameraInputsManager));
  48490. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48491. })(BABYLON || (BABYLON = {}));
  48492. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48493. var BABYLON;
  48494. (function (BABYLON) {
  48495. var ArcRotateCamera = /** @class */ (function (_super) {
  48496. __extends(ArcRotateCamera, _super);
  48497. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48498. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48499. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48500. _this.inertialAlphaOffset = 0;
  48501. _this.inertialBetaOffset = 0;
  48502. _this.inertialRadiusOffset = 0;
  48503. _this.lowerAlphaLimit = null;
  48504. _this.upperAlphaLimit = null;
  48505. _this.lowerBetaLimit = 0.01;
  48506. _this.upperBetaLimit = Math.PI;
  48507. _this.lowerRadiusLimit = null;
  48508. _this.upperRadiusLimit = null;
  48509. _this.inertialPanningX = 0;
  48510. _this.inertialPanningY = 0;
  48511. _this.pinchToPanMaxDistance = 20;
  48512. _this.panningDistanceLimit = null;
  48513. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48514. _this.panningInertia = 0.9;
  48515. //-- end properties for backward compatibility for inputs
  48516. _this.zoomOnFactor = 1;
  48517. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48518. _this.allowUpsideDown = true;
  48519. _this._viewMatrix = new BABYLON.Matrix();
  48520. // Panning
  48521. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48522. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48523. _this.checkCollisions = false;
  48524. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48525. _this._previousPosition = BABYLON.Vector3.Zero();
  48526. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48527. _this._newPosition = BABYLON.Vector3.Zero();
  48528. _this._computationVector = BABYLON.Vector3.Zero();
  48529. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48530. if (collidedMesh === void 0) { collidedMesh = null; }
  48531. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48532. newPosition.multiplyInPlace(_this._collider._radius);
  48533. }
  48534. if (!collidedMesh) {
  48535. _this._previousPosition.copyFrom(_this.position);
  48536. }
  48537. else {
  48538. _this.setPosition(newPosition);
  48539. if (_this.onCollide) {
  48540. _this.onCollide(collidedMesh);
  48541. }
  48542. }
  48543. // Recompute because of constraints
  48544. var cosa = Math.cos(_this.alpha);
  48545. var sina = Math.sin(_this.alpha);
  48546. var cosb = Math.cos(_this.beta);
  48547. var sinb = Math.sin(_this.beta);
  48548. if (sinb === 0) {
  48549. sinb = 0.0001;
  48550. }
  48551. var target = _this._getTargetPosition();
  48552. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48553. target.addToRef(_this._computationVector, _this._newPosition);
  48554. _this.position.copyFrom(_this._newPosition);
  48555. var up = _this.upVector;
  48556. if (_this.allowUpsideDown && _this.beta < 0) {
  48557. up = up.clone();
  48558. up = up.negate();
  48559. }
  48560. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48561. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48562. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48563. _this._collisionTriggered = false;
  48564. };
  48565. _this._target = BABYLON.Vector3.Zero();
  48566. if (target) {
  48567. _this.setTarget(target);
  48568. }
  48569. _this.alpha = alpha;
  48570. _this.beta = beta;
  48571. _this.radius = radius;
  48572. _this.getViewMatrix();
  48573. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48574. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48575. return _this;
  48576. }
  48577. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48578. get: function () {
  48579. return this._target;
  48580. },
  48581. set: function (value) {
  48582. this.setTarget(value);
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48588. //-- begin properties for backward compatibility for inputs
  48589. get: function () {
  48590. var pointers = this.inputs.attached["pointers"];
  48591. if (pointers)
  48592. return pointers.angularSensibilityX;
  48593. return 0;
  48594. },
  48595. set: function (value) {
  48596. var pointers = this.inputs.attached["pointers"];
  48597. if (pointers) {
  48598. pointers.angularSensibilityX = value;
  48599. }
  48600. },
  48601. enumerable: true,
  48602. configurable: true
  48603. });
  48604. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48605. get: function () {
  48606. var pointers = this.inputs.attached["pointers"];
  48607. if (pointers)
  48608. return pointers.angularSensibilityY;
  48609. return 0;
  48610. },
  48611. set: function (value) {
  48612. var pointers = this.inputs.attached["pointers"];
  48613. if (pointers) {
  48614. pointers.angularSensibilityY = value;
  48615. }
  48616. },
  48617. enumerable: true,
  48618. configurable: true
  48619. });
  48620. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48621. get: function () {
  48622. var pointers = this.inputs.attached["pointers"];
  48623. if (pointers)
  48624. return pointers.pinchPrecision;
  48625. return 0;
  48626. },
  48627. set: function (value) {
  48628. var pointers = this.inputs.attached["pointers"];
  48629. if (pointers) {
  48630. pointers.pinchPrecision = value;
  48631. }
  48632. },
  48633. enumerable: true,
  48634. configurable: true
  48635. });
  48636. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48637. get: function () {
  48638. var pointers = this.inputs.attached["pointers"];
  48639. if (pointers)
  48640. return pointers.pinchDeltaPercentage;
  48641. return 0;
  48642. },
  48643. set: function (value) {
  48644. var pointers = this.inputs.attached["pointers"];
  48645. if (pointers) {
  48646. pointers.pinchDeltaPercentage = value;
  48647. }
  48648. },
  48649. enumerable: true,
  48650. configurable: true
  48651. });
  48652. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48653. get: function () {
  48654. var pointers = this.inputs.attached["pointers"];
  48655. if (pointers)
  48656. return pointers.panningSensibility;
  48657. return 0;
  48658. },
  48659. set: function (value) {
  48660. var pointers = this.inputs.attached["pointers"];
  48661. if (pointers) {
  48662. pointers.panningSensibility = value;
  48663. }
  48664. },
  48665. enumerable: true,
  48666. configurable: true
  48667. });
  48668. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48669. get: function () {
  48670. var keyboard = this.inputs.attached["keyboard"];
  48671. if (keyboard)
  48672. return keyboard.keysUp;
  48673. return [];
  48674. },
  48675. set: function (value) {
  48676. var keyboard = this.inputs.attached["keyboard"];
  48677. if (keyboard)
  48678. keyboard.keysUp = value;
  48679. },
  48680. enumerable: true,
  48681. configurable: true
  48682. });
  48683. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48684. get: function () {
  48685. var keyboard = this.inputs.attached["keyboard"];
  48686. if (keyboard)
  48687. return keyboard.keysDown;
  48688. return [];
  48689. },
  48690. set: function (value) {
  48691. var keyboard = this.inputs.attached["keyboard"];
  48692. if (keyboard)
  48693. keyboard.keysDown = value;
  48694. },
  48695. enumerable: true,
  48696. configurable: true
  48697. });
  48698. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48699. get: function () {
  48700. var keyboard = this.inputs.attached["keyboard"];
  48701. if (keyboard)
  48702. return keyboard.keysLeft;
  48703. return [];
  48704. },
  48705. set: function (value) {
  48706. var keyboard = this.inputs.attached["keyboard"];
  48707. if (keyboard)
  48708. keyboard.keysLeft = value;
  48709. },
  48710. enumerable: true,
  48711. configurable: true
  48712. });
  48713. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48714. get: function () {
  48715. var keyboard = this.inputs.attached["keyboard"];
  48716. if (keyboard)
  48717. return keyboard.keysRight;
  48718. return [];
  48719. },
  48720. set: function (value) {
  48721. var keyboard = this.inputs.attached["keyboard"];
  48722. if (keyboard)
  48723. keyboard.keysRight = value;
  48724. },
  48725. enumerable: true,
  48726. configurable: true
  48727. });
  48728. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48729. get: function () {
  48730. var mousewheel = this.inputs.attached["mousewheel"];
  48731. if (mousewheel)
  48732. return mousewheel.wheelPrecision;
  48733. return 0;
  48734. },
  48735. set: function (value) {
  48736. var mousewheel = this.inputs.attached["mousewheel"];
  48737. if (mousewheel)
  48738. mousewheel.wheelPrecision = value;
  48739. },
  48740. enumerable: true,
  48741. configurable: true
  48742. });
  48743. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48744. get: function () {
  48745. var mousewheel = this.inputs.attached["mousewheel"];
  48746. if (mousewheel)
  48747. return mousewheel.wheelDeltaPercentage;
  48748. return 0;
  48749. },
  48750. set: function (value) {
  48751. var mousewheel = this.inputs.attached["mousewheel"];
  48752. if (mousewheel)
  48753. mousewheel.wheelDeltaPercentage = value;
  48754. },
  48755. enumerable: true,
  48756. configurable: true
  48757. });
  48758. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48759. get: function () {
  48760. return this._bouncingBehavior;
  48761. },
  48762. enumerable: true,
  48763. configurable: true
  48764. });
  48765. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48766. get: function () {
  48767. return this._bouncingBehavior != null;
  48768. },
  48769. set: function (value) {
  48770. if (value === this.useBouncingBehavior) {
  48771. return;
  48772. }
  48773. if (value) {
  48774. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48775. this.addBehavior(this._bouncingBehavior);
  48776. }
  48777. else if (this._bouncingBehavior) {
  48778. this.removeBehavior(this._bouncingBehavior);
  48779. this._bouncingBehavior = null;
  48780. }
  48781. },
  48782. enumerable: true,
  48783. configurable: true
  48784. });
  48785. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48786. get: function () {
  48787. return this._framingBehavior;
  48788. },
  48789. enumerable: true,
  48790. configurable: true
  48791. });
  48792. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48793. get: function () {
  48794. return this._framingBehavior != null;
  48795. },
  48796. set: function (value) {
  48797. if (value === this.useFramingBehavior) {
  48798. return;
  48799. }
  48800. if (value) {
  48801. this._framingBehavior = new BABYLON.FramingBehavior();
  48802. this.addBehavior(this._framingBehavior);
  48803. }
  48804. else if (this._framingBehavior) {
  48805. this.removeBehavior(this._framingBehavior);
  48806. this._framingBehavior = null;
  48807. }
  48808. },
  48809. enumerable: true,
  48810. configurable: true
  48811. });
  48812. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48813. get: function () {
  48814. return this._autoRotationBehavior;
  48815. },
  48816. enumerable: true,
  48817. configurable: true
  48818. });
  48819. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48820. get: function () {
  48821. return this._autoRotationBehavior != null;
  48822. },
  48823. set: function (value) {
  48824. if (value === this.useAutoRotationBehavior) {
  48825. return;
  48826. }
  48827. if (value) {
  48828. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48829. this.addBehavior(this._autoRotationBehavior);
  48830. }
  48831. else if (this._autoRotationBehavior) {
  48832. this.removeBehavior(this._autoRotationBehavior);
  48833. this._autoRotationBehavior = null;
  48834. }
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. // Cache
  48840. ArcRotateCamera.prototype._initCache = function () {
  48841. _super.prototype._initCache.call(this);
  48842. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48843. this._cache.alpha = undefined;
  48844. this._cache.beta = undefined;
  48845. this._cache.radius = undefined;
  48846. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48847. };
  48848. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48849. if (!ignoreParentClass) {
  48850. _super.prototype._updateCache.call(this);
  48851. }
  48852. this._cache._target.copyFrom(this._getTargetPosition());
  48853. this._cache.alpha = this.alpha;
  48854. this._cache.beta = this.beta;
  48855. this._cache.radius = this.radius;
  48856. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48857. };
  48858. ArcRotateCamera.prototype._getTargetPosition = function () {
  48859. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48860. var pos = this._targetHost.getAbsolutePosition();
  48861. if (this._targetBoundingCenter) {
  48862. pos.addToRef(this._targetBoundingCenter, this._target);
  48863. }
  48864. else {
  48865. this._target.copyFrom(pos);
  48866. }
  48867. }
  48868. var lockedTargetPosition = this._getLockedTargetPosition();
  48869. if (lockedTargetPosition) {
  48870. return lockedTargetPosition;
  48871. }
  48872. return this._target;
  48873. };
  48874. ArcRotateCamera.prototype.storeState = function () {
  48875. this._storedAlpha = this.alpha;
  48876. this._storedBeta = this.beta;
  48877. this._storedRadius = this.radius;
  48878. this._storedTarget = this._getTargetPosition().clone();
  48879. return _super.prototype.storeState.call(this);
  48880. };
  48881. /**
  48882. * Restored camera state. You must call storeState() first
  48883. */
  48884. ArcRotateCamera.prototype._restoreStateValues = function () {
  48885. if (!_super.prototype._restoreStateValues.call(this)) {
  48886. return false;
  48887. }
  48888. this.alpha = this._storedAlpha;
  48889. this.beta = this._storedBeta;
  48890. this.radius = this._storedRadius;
  48891. this.setTarget(this._storedTarget.clone());
  48892. this.inertialAlphaOffset = 0;
  48893. this.inertialBetaOffset = 0;
  48894. this.inertialRadiusOffset = 0;
  48895. this.inertialPanningX = 0;
  48896. this.inertialPanningY = 0;
  48897. return true;
  48898. };
  48899. // Synchronized
  48900. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48901. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48902. return false;
  48903. return this._cache._target.equals(this._getTargetPosition())
  48904. && this._cache.alpha === this.alpha
  48905. && this._cache.beta === this.beta
  48906. && this._cache.radius === this.radius
  48907. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48908. };
  48909. // Methods
  48910. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48911. var _this = this;
  48912. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48913. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48914. this._useCtrlForPanning = useCtrlForPanning;
  48915. this._panningMouseButton = panningMouseButton;
  48916. this.inputs.attachElement(element, noPreventDefault);
  48917. this._reset = function () {
  48918. _this.inertialAlphaOffset = 0;
  48919. _this.inertialBetaOffset = 0;
  48920. _this.inertialRadiusOffset = 0;
  48921. _this.inertialPanningX = 0;
  48922. _this.inertialPanningY = 0;
  48923. };
  48924. };
  48925. ArcRotateCamera.prototype.detachControl = function (element) {
  48926. this.inputs.detachElement(element);
  48927. if (this._reset) {
  48928. this._reset();
  48929. }
  48930. };
  48931. ArcRotateCamera.prototype._checkInputs = function () {
  48932. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48933. if (this._collisionTriggered) {
  48934. return;
  48935. }
  48936. this.inputs.checkInputs();
  48937. // Inertia
  48938. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48939. var inertialAlphaOffset = this.inertialAlphaOffset;
  48940. if (this.beta <= 0)
  48941. inertialAlphaOffset *= -1;
  48942. if (this.getScene().useRightHandedSystem)
  48943. inertialAlphaOffset *= -1;
  48944. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48945. inertialAlphaOffset *= -1;
  48946. this.alpha += inertialAlphaOffset;
  48947. this.beta += this.inertialBetaOffset;
  48948. this.radius -= this.inertialRadiusOffset;
  48949. this.inertialAlphaOffset *= this.inertia;
  48950. this.inertialBetaOffset *= this.inertia;
  48951. this.inertialRadiusOffset *= this.inertia;
  48952. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48953. this.inertialAlphaOffset = 0;
  48954. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48955. this.inertialBetaOffset = 0;
  48956. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48957. this.inertialRadiusOffset = 0;
  48958. }
  48959. // Panning inertia
  48960. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48961. if (!this._localDirection) {
  48962. this._localDirection = BABYLON.Vector3.Zero();
  48963. this._transformedDirection = BABYLON.Vector3.Zero();
  48964. }
  48965. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48966. this._localDirection.multiplyInPlace(this.panningAxis);
  48967. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48968. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48969. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48970. if (!this.panningAxis.y) {
  48971. this._transformedDirection.y = 0;
  48972. }
  48973. if (!this._targetHost) {
  48974. if (this.panningDistanceLimit) {
  48975. this._transformedDirection.addInPlace(this._target);
  48976. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48977. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48978. this._target.copyFrom(this._transformedDirection);
  48979. }
  48980. }
  48981. else {
  48982. this._target.addInPlace(this._transformedDirection);
  48983. }
  48984. }
  48985. this.inertialPanningX *= this.panningInertia;
  48986. this.inertialPanningY *= this.panningInertia;
  48987. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48988. this.inertialPanningX = 0;
  48989. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48990. this.inertialPanningY = 0;
  48991. }
  48992. // Limits
  48993. this._checkLimits();
  48994. _super.prototype._checkInputs.call(this);
  48995. };
  48996. ArcRotateCamera.prototype._checkLimits = function () {
  48997. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48998. if (this.allowUpsideDown && this.beta > Math.PI) {
  48999. this.beta = this.beta - (2 * Math.PI);
  49000. }
  49001. }
  49002. else {
  49003. if (this.beta < this.lowerBetaLimit) {
  49004. this.beta = this.lowerBetaLimit;
  49005. }
  49006. }
  49007. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49008. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49009. this.beta = this.beta + (2 * Math.PI);
  49010. }
  49011. }
  49012. else {
  49013. if (this.beta > this.upperBetaLimit) {
  49014. this.beta = this.upperBetaLimit;
  49015. }
  49016. }
  49017. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49018. this.alpha = this.lowerAlphaLimit;
  49019. }
  49020. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49021. this.alpha = this.upperAlphaLimit;
  49022. }
  49023. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49024. this.radius = this.lowerRadiusLimit;
  49025. }
  49026. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49027. this.radius = this.upperRadiusLimit;
  49028. }
  49029. };
  49030. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49031. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49032. this.radius = this._computationVector.length();
  49033. if (this.radius === 0) {
  49034. this.radius = 0.0001; // Just to avoid division by zero
  49035. }
  49036. // Alpha
  49037. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49038. if (this._computationVector.z < 0) {
  49039. this.alpha = 2 * Math.PI - this.alpha;
  49040. }
  49041. // Beta
  49042. this.beta = Math.acos(this._computationVector.y / this.radius);
  49043. this._checkLimits();
  49044. };
  49045. ArcRotateCamera.prototype.setPosition = function (position) {
  49046. if (this.position.equals(position)) {
  49047. return;
  49048. }
  49049. this.position.copyFrom(position);
  49050. this.rebuildAnglesAndRadius();
  49051. };
  49052. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49053. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49054. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49055. if (target.getBoundingInfo) {
  49056. if (toBoundingCenter) {
  49057. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49058. }
  49059. else {
  49060. this._targetBoundingCenter = null;
  49061. }
  49062. this._targetHost = target;
  49063. this._target = this._getTargetPosition();
  49064. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49065. }
  49066. else {
  49067. var newTarget = target;
  49068. var currentTarget = this._getTargetPosition();
  49069. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49070. return;
  49071. }
  49072. this._targetHost = null;
  49073. this._target = newTarget;
  49074. this._targetBoundingCenter = null;
  49075. this.onMeshTargetChangedObservable.notifyObservers(null);
  49076. }
  49077. this.rebuildAnglesAndRadius();
  49078. };
  49079. ArcRotateCamera.prototype._getViewMatrix = function () {
  49080. // Compute
  49081. var cosa = Math.cos(this.alpha);
  49082. var sina = Math.sin(this.alpha);
  49083. var cosb = Math.cos(this.beta);
  49084. var sinb = Math.sin(this.beta);
  49085. if (sinb === 0) {
  49086. sinb = 0.0001;
  49087. }
  49088. var target = this._getTargetPosition();
  49089. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49090. target.addToRef(this._computationVector, this._newPosition);
  49091. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49092. if (!this._collider) {
  49093. this._collider = new BABYLON.Collider();
  49094. }
  49095. this._collider._radius = this.collisionRadius;
  49096. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49097. this._collisionTriggered = true;
  49098. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49099. }
  49100. else {
  49101. this.position.copyFrom(this._newPosition);
  49102. var up = this.upVector;
  49103. if (this.allowUpsideDown && sinb < 0) {
  49104. up = up.clone();
  49105. up = up.negate();
  49106. }
  49107. this._computeViewMatrix(this.position, target, up);
  49108. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49109. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49110. }
  49111. this._currentTarget = target;
  49112. return this._viewMatrix;
  49113. };
  49114. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49115. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49116. meshes = meshes || this.getScene().meshes;
  49117. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49118. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49119. this.radius = distance * this.zoomOnFactor;
  49120. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49121. };
  49122. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49123. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49124. var meshesOrMinMaxVector;
  49125. var distance;
  49126. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49127. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49128. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49129. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49130. }
  49131. else { //minMaxVector and distance
  49132. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49133. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49134. distance = minMaxVectorAndDistance.distance;
  49135. }
  49136. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49137. if (!doNotUpdateMaxZ) {
  49138. this.maxZ = distance * 2;
  49139. }
  49140. };
  49141. /**
  49142. * @override
  49143. * Override Camera.createRigCamera
  49144. */
  49145. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49146. var alphaShift = 0;
  49147. switch (this.cameraRigMode) {
  49148. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49150. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49151. case BABYLON.Camera.RIG_MODE_VR:
  49152. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49153. break;
  49154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49155. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49156. break;
  49157. }
  49158. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49159. rigCam._cameraRigParams = {};
  49160. return rigCam;
  49161. };
  49162. /**
  49163. * @override
  49164. * Override Camera._updateRigCameras
  49165. */
  49166. ArcRotateCamera.prototype._updateRigCameras = function () {
  49167. var camLeft = this._rigCameras[0];
  49168. var camRight = this._rigCameras[1];
  49169. camLeft.beta = camRight.beta = this.beta;
  49170. camLeft.radius = camRight.radius = this.radius;
  49171. switch (this.cameraRigMode) {
  49172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49175. case BABYLON.Camera.RIG_MODE_VR:
  49176. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49177. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49178. break;
  49179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49180. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49181. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49182. break;
  49183. }
  49184. _super.prototype._updateRigCameras.call(this);
  49185. };
  49186. ArcRotateCamera.prototype.dispose = function () {
  49187. this.inputs.clear();
  49188. _super.prototype.dispose.call(this);
  49189. };
  49190. ArcRotateCamera.prototype.getClassName = function () {
  49191. return "ArcRotateCamera";
  49192. };
  49193. __decorate([
  49194. BABYLON.serialize()
  49195. ], ArcRotateCamera.prototype, "alpha", void 0);
  49196. __decorate([
  49197. BABYLON.serialize()
  49198. ], ArcRotateCamera.prototype, "beta", void 0);
  49199. __decorate([
  49200. BABYLON.serialize()
  49201. ], ArcRotateCamera.prototype, "radius", void 0);
  49202. __decorate([
  49203. BABYLON.serializeAsVector3("target")
  49204. ], ArcRotateCamera.prototype, "_target", void 0);
  49205. __decorate([
  49206. BABYLON.serialize()
  49207. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49208. __decorate([
  49209. BABYLON.serialize()
  49210. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49211. __decorate([
  49212. BABYLON.serialize()
  49213. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49214. __decorate([
  49215. BABYLON.serialize()
  49216. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49217. __decorate([
  49218. BABYLON.serialize()
  49219. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49220. __decorate([
  49221. BABYLON.serialize()
  49222. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49223. __decorate([
  49224. BABYLON.serialize()
  49225. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49226. __decorate([
  49227. BABYLON.serialize()
  49228. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49229. __decorate([
  49230. BABYLON.serialize()
  49231. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49232. __decorate([
  49233. BABYLON.serialize()
  49234. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49235. __decorate([
  49236. BABYLON.serialize()
  49237. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49238. __decorate([
  49239. BABYLON.serialize()
  49240. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49241. __decorate([
  49242. BABYLON.serialize()
  49243. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49244. __decorate([
  49245. BABYLON.serializeAsVector3()
  49246. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49247. __decorate([
  49248. BABYLON.serialize()
  49249. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49250. __decorate([
  49251. BABYLON.serialize()
  49252. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49253. __decorate([
  49254. BABYLON.serialize()
  49255. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49256. return ArcRotateCamera;
  49257. }(BABYLON.TargetCamera));
  49258. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49259. })(BABYLON || (BABYLON = {}));
  49260. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49261. var BABYLON;
  49262. (function (BABYLON) {
  49263. /**
  49264. * The HemisphericLight simulates the ambient environment light,
  49265. * so the passed direction is the light reflection direction, not the incoming direction.
  49266. */
  49267. var HemisphericLight = /** @class */ (function (_super) {
  49268. __extends(HemisphericLight, _super);
  49269. /**
  49270. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49271. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49272. * The HemisphericLight can't cast shadows.
  49273. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49274. * @param name The friendly name of the light
  49275. * @param direction The direction of the light reflection
  49276. * @param scene The scene the light belongs to
  49277. */
  49278. function HemisphericLight(name, direction, scene) {
  49279. var _this = _super.call(this, name, scene) || this;
  49280. /**
  49281. * The groundColor is the light in the opposite direction to the one specified during creation.
  49282. * 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.
  49283. */
  49284. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49285. _this.direction = direction || BABYLON.Vector3.Up();
  49286. return _this;
  49287. }
  49288. HemisphericLight.prototype._buildUniformLayout = function () {
  49289. this._uniformBuffer.addUniform("vLightData", 4);
  49290. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49291. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49292. this._uniformBuffer.addUniform("vLightGround", 3);
  49293. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49294. this._uniformBuffer.addUniform("depthValues", 2);
  49295. this._uniformBuffer.create();
  49296. };
  49297. /**
  49298. * Returns the string "HemisphericLight".
  49299. * @return The class name
  49300. */
  49301. HemisphericLight.prototype.getClassName = function () {
  49302. return "HemisphericLight";
  49303. };
  49304. /**
  49305. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49306. * Returns the updated direction.
  49307. * @param target The target the direction should point to
  49308. * @return The computed direction
  49309. */
  49310. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49311. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49312. return this.direction;
  49313. };
  49314. /**
  49315. * Returns the shadow generator associated to the light.
  49316. * @returns Always null for hemispheric lights because it does not support shadows.
  49317. */
  49318. HemisphericLight.prototype.getShadowGenerator = function () {
  49319. return null;
  49320. };
  49321. /**
  49322. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49323. * @param effect The effect to update
  49324. * @param lightIndex The index of the light in the effect to update
  49325. * @returns The hemispheric light
  49326. */
  49327. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49328. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49329. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49330. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49331. return this;
  49332. };
  49333. /**
  49334. * @hidden internal use only.
  49335. */
  49336. HemisphericLight.prototype._getWorldMatrix = function () {
  49337. if (!this._worldMatrix) {
  49338. this._worldMatrix = BABYLON.Matrix.Identity();
  49339. }
  49340. return this._worldMatrix;
  49341. };
  49342. /**
  49343. * Returns the integer 3.
  49344. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49345. */
  49346. HemisphericLight.prototype.getTypeID = function () {
  49347. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49348. };
  49349. __decorate([
  49350. BABYLON.serializeAsColor3()
  49351. ], HemisphericLight.prototype, "groundColor", void 0);
  49352. __decorate([
  49353. BABYLON.serializeAsVector3()
  49354. ], HemisphericLight.prototype, "direction", void 0);
  49355. return HemisphericLight;
  49356. }(BABYLON.Light));
  49357. BABYLON.HemisphericLight = HemisphericLight;
  49358. })(BABYLON || (BABYLON = {}));
  49359. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49360. var BABYLON;
  49361. (function (BABYLON) {
  49362. /**
  49363. * Base implementation IShadowLight
  49364. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49365. */
  49366. var ShadowLight = /** @class */ (function (_super) {
  49367. __extends(ShadowLight, _super);
  49368. function ShadowLight() {
  49369. var _this = _super !== null && _super.apply(this, arguments) || this;
  49370. _this._needProjectionMatrixCompute = true;
  49371. return _this;
  49372. }
  49373. ShadowLight.prototype._setPosition = function (value) {
  49374. this._position = value;
  49375. };
  49376. Object.defineProperty(ShadowLight.prototype, "position", {
  49377. /**
  49378. * Sets the position the shadow will be casted from. Also use as the light position for both
  49379. * point and spot lights.
  49380. */
  49381. get: function () {
  49382. return this._position;
  49383. },
  49384. /**
  49385. * Sets the position the shadow will be casted from. Also use as the light position for both
  49386. * point and spot lights.
  49387. */
  49388. set: function (value) {
  49389. this._setPosition(value);
  49390. },
  49391. enumerable: true,
  49392. configurable: true
  49393. });
  49394. ShadowLight.prototype._setDirection = function (value) {
  49395. this._direction = value;
  49396. };
  49397. Object.defineProperty(ShadowLight.prototype, "direction", {
  49398. /**
  49399. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49400. * Also use as the light direction on spot and directional lights.
  49401. */
  49402. get: function () {
  49403. return this._direction;
  49404. },
  49405. /**
  49406. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49407. * Also use as the light direction on spot and directional lights.
  49408. */
  49409. set: function (value) {
  49410. this._setDirection(value);
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49416. /**
  49417. * Gets the shadow projection clipping minimum z value.
  49418. */
  49419. get: function () {
  49420. return this._shadowMinZ;
  49421. },
  49422. /**
  49423. * Sets the shadow projection clipping minimum z value.
  49424. */
  49425. set: function (value) {
  49426. this._shadowMinZ = value;
  49427. this.forceProjectionMatrixCompute();
  49428. },
  49429. enumerable: true,
  49430. configurable: true
  49431. });
  49432. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49433. /**
  49434. * Sets the shadow projection clipping maximum z value.
  49435. */
  49436. get: function () {
  49437. return this._shadowMaxZ;
  49438. },
  49439. /**
  49440. * Gets the shadow projection clipping maximum z value.
  49441. */
  49442. set: function (value) {
  49443. this._shadowMaxZ = value;
  49444. this.forceProjectionMatrixCompute();
  49445. },
  49446. enumerable: true,
  49447. configurable: true
  49448. });
  49449. /**
  49450. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49451. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49452. */
  49453. ShadowLight.prototype.computeTransformedInformation = function () {
  49454. if (this.parent && this.parent.getWorldMatrix) {
  49455. if (!this.transformedPosition) {
  49456. this.transformedPosition = BABYLON.Vector3.Zero();
  49457. }
  49458. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49459. // In case the direction is present.
  49460. if (this.direction) {
  49461. if (!this.transformedDirection) {
  49462. this.transformedDirection = BABYLON.Vector3.Zero();
  49463. }
  49464. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49465. }
  49466. return true;
  49467. }
  49468. return false;
  49469. };
  49470. /**
  49471. * Return the depth scale used for the shadow map.
  49472. * @returns the depth scale.
  49473. */
  49474. ShadowLight.prototype.getDepthScale = function () {
  49475. return 50.0;
  49476. };
  49477. /**
  49478. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49479. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49480. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49481. */
  49482. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49483. return this.transformedDirection ? this.transformedDirection : this.direction;
  49484. };
  49485. /**
  49486. * Returns the ShadowLight absolute position in the World.
  49487. * @returns the position vector in world space
  49488. */
  49489. ShadowLight.prototype.getAbsolutePosition = function () {
  49490. return this.transformedPosition ? this.transformedPosition : this.position;
  49491. };
  49492. /**
  49493. * Sets the ShadowLight direction toward the passed target.
  49494. * @param target The point tot target in local space
  49495. * @returns the updated ShadowLight direction
  49496. */
  49497. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49498. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49499. return this.direction;
  49500. };
  49501. /**
  49502. * Returns the light rotation in euler definition.
  49503. * @returns the x y z rotation in local space.
  49504. */
  49505. ShadowLight.prototype.getRotation = function () {
  49506. this.direction.normalize();
  49507. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49508. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49509. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49510. };
  49511. /**
  49512. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49513. * @returns true if a cube texture needs to be use
  49514. */
  49515. ShadowLight.prototype.needCube = function () {
  49516. return false;
  49517. };
  49518. /**
  49519. * Detects if the projection matrix requires to be recomputed this frame.
  49520. * @returns true if it requires to be recomputed otherwise, false.
  49521. */
  49522. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49523. return this._needProjectionMatrixCompute;
  49524. };
  49525. /**
  49526. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49527. */
  49528. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49529. this._needProjectionMatrixCompute = true;
  49530. };
  49531. /**
  49532. * Get the world matrix of the sahdow lights.
  49533. * @hidden Internal Use Only
  49534. */
  49535. ShadowLight.prototype._getWorldMatrix = function () {
  49536. if (!this._worldMatrix) {
  49537. this._worldMatrix = BABYLON.Matrix.Identity();
  49538. }
  49539. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49540. return this._worldMatrix;
  49541. };
  49542. /**
  49543. * Gets the minZ used for shadow according to both the scene and the light.
  49544. * @param activeCamera The camera we are returning the min for
  49545. * @returns the depth min z
  49546. */
  49547. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49548. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49549. };
  49550. /**
  49551. * Gets the maxZ used for shadow according to both the scene and the light.
  49552. * @param activeCamera The camera we are returning the max for
  49553. * @returns the depth max z
  49554. */
  49555. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49556. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49557. };
  49558. /**
  49559. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49560. * @param matrix The materix to updated with the projection information
  49561. * @param viewMatrix The transform matrix of the light
  49562. * @param renderList The list of mesh to render in the map
  49563. * @returns The current light
  49564. */
  49565. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49566. if (this.customProjectionMatrixBuilder) {
  49567. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49568. }
  49569. else {
  49570. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49571. }
  49572. return this;
  49573. };
  49574. __decorate([
  49575. BABYLON.serializeAsVector3()
  49576. ], ShadowLight.prototype, "position", null);
  49577. __decorate([
  49578. BABYLON.serializeAsVector3()
  49579. ], ShadowLight.prototype, "direction", null);
  49580. __decorate([
  49581. BABYLON.serialize()
  49582. ], ShadowLight.prototype, "shadowMinZ", null);
  49583. __decorate([
  49584. BABYLON.serialize()
  49585. ], ShadowLight.prototype, "shadowMaxZ", null);
  49586. return ShadowLight;
  49587. }(BABYLON.Light));
  49588. BABYLON.ShadowLight = ShadowLight;
  49589. })(BABYLON || (BABYLON = {}));
  49590. //# sourceMappingURL=babylon.shadowLight.js.map
  49591. var BABYLON;
  49592. (function (BABYLON) {
  49593. /**
  49594. * A point light is a light defined by an unique point in world space.
  49595. * The light is emitted in every direction from this point.
  49596. * A good example of a point light is a standard light bulb.
  49597. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49598. */
  49599. var PointLight = /** @class */ (function (_super) {
  49600. __extends(PointLight, _super);
  49601. /**
  49602. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49603. * A PointLight emits the light in every direction.
  49604. * It can cast shadows.
  49605. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49606. * ```javascript
  49607. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49608. * ```
  49609. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49610. * @param name The light friendly name
  49611. * @param position The position of the point light in the scene
  49612. * @param scene The scene the lights belongs to
  49613. */
  49614. function PointLight(name, position, scene) {
  49615. var _this = _super.call(this, name, scene) || this;
  49616. _this._shadowAngle = Math.PI / 2;
  49617. _this.position = position;
  49618. return _this;
  49619. }
  49620. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49621. /**
  49622. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49623. * This specifies what angle the shadow will use to be created.
  49624. *
  49625. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49626. */
  49627. get: function () {
  49628. return this._shadowAngle;
  49629. },
  49630. /**
  49631. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49632. * This specifies what angle the shadow will use to be created.
  49633. *
  49634. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49635. */
  49636. set: function (value) {
  49637. this._shadowAngle = value;
  49638. this.forceProjectionMatrixCompute();
  49639. },
  49640. enumerable: true,
  49641. configurable: true
  49642. });
  49643. Object.defineProperty(PointLight.prototype, "direction", {
  49644. /**
  49645. * Gets the direction if it has been set.
  49646. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49647. */
  49648. get: function () {
  49649. return this._direction;
  49650. },
  49651. /**
  49652. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49653. */
  49654. set: function (value) {
  49655. var previousNeedCube = this.needCube();
  49656. this._direction = value;
  49657. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49658. this._shadowGenerator.recreateShadowMap();
  49659. }
  49660. },
  49661. enumerable: true,
  49662. configurable: true
  49663. });
  49664. /**
  49665. * Returns the string "PointLight"
  49666. * @returns the class name
  49667. */
  49668. PointLight.prototype.getClassName = function () {
  49669. return "PointLight";
  49670. };
  49671. /**
  49672. * Returns the integer 0.
  49673. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49674. */
  49675. PointLight.prototype.getTypeID = function () {
  49676. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49677. };
  49678. /**
  49679. * Specifies wether or not the shadowmap should be a cube texture.
  49680. * @returns true if the shadowmap needs to be a cube texture.
  49681. */
  49682. PointLight.prototype.needCube = function () {
  49683. return !this.direction;
  49684. };
  49685. /**
  49686. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49687. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49688. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49689. */
  49690. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49691. if (this.direction) {
  49692. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49693. }
  49694. else {
  49695. switch (faceIndex) {
  49696. case 0:
  49697. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49698. case 1:
  49699. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49700. case 2:
  49701. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49702. case 3:
  49703. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49704. case 4:
  49705. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49706. case 5:
  49707. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49708. }
  49709. }
  49710. return BABYLON.Vector3.Zero();
  49711. };
  49712. /**
  49713. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49714. * - fov = PI / 2
  49715. * - aspect ratio : 1.0
  49716. * - z-near and far equal to the active camera minZ and maxZ.
  49717. * Returns the PointLight.
  49718. */
  49719. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49720. var activeCamera = this.getScene().activeCamera;
  49721. if (!activeCamera) {
  49722. return;
  49723. }
  49724. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49725. };
  49726. PointLight.prototype._buildUniformLayout = function () {
  49727. this._uniformBuffer.addUniform("vLightData", 4);
  49728. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49729. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49730. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49731. this._uniformBuffer.addUniform("depthValues", 2);
  49732. this._uniformBuffer.create();
  49733. };
  49734. /**
  49735. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49736. * @param effect The effect to update
  49737. * @param lightIndex The index of the light in the effect to update
  49738. * @returns The point light
  49739. */
  49740. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49741. if (this.computeTransformedInformation()) {
  49742. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49743. return this;
  49744. }
  49745. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49746. return this;
  49747. };
  49748. __decorate([
  49749. BABYLON.serialize()
  49750. ], PointLight.prototype, "shadowAngle", null);
  49751. return PointLight;
  49752. }(BABYLON.ShadowLight));
  49753. BABYLON.PointLight = PointLight;
  49754. })(BABYLON || (BABYLON = {}));
  49755. //# sourceMappingURL=babylon.pointLight.js.map
  49756. var BABYLON;
  49757. (function (BABYLON) {
  49758. /**
  49759. * A directional light is defined by a direction (what a surprise!).
  49760. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49761. * 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.
  49762. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49763. */
  49764. var DirectionalLight = /** @class */ (function (_super) {
  49765. __extends(DirectionalLight, _super);
  49766. /**
  49767. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49768. * The directional light is emitted from everywhere in the given direction.
  49769. * It can cast shawdows.
  49770. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49771. * @param name The friendly name of the light
  49772. * @param direction The direction of the light
  49773. * @param scene The scene the light belongs to
  49774. */
  49775. function DirectionalLight(name, direction, scene) {
  49776. var _this = _super.call(this, name, scene) || this;
  49777. _this._shadowFrustumSize = 0;
  49778. _this._shadowOrthoScale = 0.1;
  49779. /**
  49780. * Automatically compute the projection matrix to best fit (including all the casters)
  49781. * on each frame.
  49782. */
  49783. _this.autoUpdateExtends = true;
  49784. // Cache
  49785. _this._orthoLeft = Number.MAX_VALUE;
  49786. _this._orthoRight = Number.MIN_VALUE;
  49787. _this._orthoTop = Number.MIN_VALUE;
  49788. _this._orthoBottom = Number.MAX_VALUE;
  49789. _this.position = direction.scale(-1.0);
  49790. _this.direction = direction;
  49791. return _this;
  49792. }
  49793. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49794. /**
  49795. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49796. */
  49797. get: function () {
  49798. return this._shadowFrustumSize;
  49799. },
  49800. /**
  49801. * Specifies a fix frustum size for the shadow generation.
  49802. */
  49803. set: function (value) {
  49804. this._shadowFrustumSize = value;
  49805. this.forceProjectionMatrixCompute();
  49806. },
  49807. enumerable: true,
  49808. configurable: true
  49809. });
  49810. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49811. /**
  49812. * Gets the shadow projection scale against the optimal computed one.
  49813. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49814. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49815. */
  49816. get: function () {
  49817. return this._shadowOrthoScale;
  49818. },
  49819. /**
  49820. * Sets the shadow projection scale against the optimal computed one.
  49821. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49822. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49823. */
  49824. set: function (value) {
  49825. this._shadowOrthoScale = value;
  49826. this.forceProjectionMatrixCompute();
  49827. },
  49828. enumerable: true,
  49829. configurable: true
  49830. });
  49831. /**
  49832. * Returns the string "DirectionalLight".
  49833. * @return The class name
  49834. */
  49835. DirectionalLight.prototype.getClassName = function () {
  49836. return "DirectionalLight";
  49837. };
  49838. /**
  49839. * Returns the integer 1.
  49840. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49841. */
  49842. DirectionalLight.prototype.getTypeID = function () {
  49843. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49844. };
  49845. /**
  49846. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49847. * Returns the DirectionalLight Shadow projection matrix.
  49848. */
  49849. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49850. if (this.shadowFrustumSize > 0) {
  49851. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49852. }
  49853. else {
  49854. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49855. }
  49856. };
  49857. /**
  49858. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49859. * Returns the DirectionalLight Shadow projection matrix.
  49860. */
  49861. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49862. var activeCamera = this.getScene().activeCamera;
  49863. if (!activeCamera) {
  49864. return;
  49865. }
  49866. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49867. };
  49868. /**
  49869. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49870. * Returns the DirectionalLight Shadow projection matrix.
  49871. */
  49872. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49873. var activeCamera = this.getScene().activeCamera;
  49874. if (!activeCamera) {
  49875. return;
  49876. }
  49877. // Check extends
  49878. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49879. var tempVector3 = BABYLON.Vector3.Zero();
  49880. this._orthoLeft = Number.MAX_VALUE;
  49881. this._orthoRight = Number.MIN_VALUE;
  49882. this._orthoTop = Number.MIN_VALUE;
  49883. this._orthoBottom = Number.MAX_VALUE;
  49884. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49885. var mesh = renderList[meshIndex];
  49886. if (!mesh) {
  49887. continue;
  49888. }
  49889. var boundingInfo = mesh.getBoundingInfo();
  49890. var boundingBox = boundingInfo.boundingBox;
  49891. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49892. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49893. if (tempVector3.x < this._orthoLeft)
  49894. this._orthoLeft = tempVector3.x;
  49895. if (tempVector3.y < this._orthoBottom)
  49896. this._orthoBottom = tempVector3.y;
  49897. if (tempVector3.x > this._orthoRight)
  49898. this._orthoRight = tempVector3.x;
  49899. if (tempVector3.y > this._orthoTop)
  49900. this._orthoTop = tempVector3.y;
  49901. }
  49902. }
  49903. }
  49904. var xOffset = this._orthoRight - this._orthoLeft;
  49905. var yOffset = this._orthoTop - this._orthoBottom;
  49906. 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);
  49907. };
  49908. DirectionalLight.prototype._buildUniformLayout = function () {
  49909. this._uniformBuffer.addUniform("vLightData", 4);
  49910. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49911. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49912. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49913. this._uniformBuffer.addUniform("depthValues", 2);
  49914. this._uniformBuffer.create();
  49915. };
  49916. /**
  49917. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49918. * @param effect The effect to update
  49919. * @param lightIndex The index of the light in the effect to update
  49920. * @returns The directional light
  49921. */
  49922. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49923. if (this.computeTransformedInformation()) {
  49924. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49925. return this;
  49926. }
  49927. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49928. return this;
  49929. };
  49930. /**
  49931. * Gets the minZ used for shadow according to both the scene and the light.
  49932. *
  49933. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49934. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49935. * @param activeCamera The camera we are returning the min for
  49936. * @returns the depth min z
  49937. */
  49938. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49939. return 1;
  49940. };
  49941. /**
  49942. * Gets the maxZ used for shadow according to both the scene and the light.
  49943. *
  49944. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49945. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49946. * @param activeCamera The camera we are returning the max for
  49947. * @returns the depth max z
  49948. */
  49949. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49950. return 1;
  49951. };
  49952. __decorate([
  49953. BABYLON.serialize()
  49954. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49955. __decorate([
  49956. BABYLON.serialize()
  49957. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49958. __decorate([
  49959. BABYLON.serialize()
  49960. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49961. return DirectionalLight;
  49962. }(BABYLON.ShadowLight));
  49963. BABYLON.DirectionalLight = DirectionalLight;
  49964. })(BABYLON || (BABYLON = {}));
  49965. //# sourceMappingURL=babylon.directionalLight.js.map
  49966. var BABYLON;
  49967. (function (BABYLON) {
  49968. /**
  49969. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49970. * These values define a cone of light starting from the position, emitting toward the direction.
  49971. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49972. * and the exponent defines the speed of the decay of the light with distance (reach).
  49973. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49974. */
  49975. var SpotLight = /** @class */ (function (_super) {
  49976. __extends(SpotLight, _super);
  49977. /**
  49978. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49979. * It can cast shadows.
  49980. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49981. * @param name The light friendly name
  49982. * @param position The position of the spot light in the scene
  49983. * @param direction The direction of the light in the scene
  49984. * @param angle The cone angle of the light in Radians
  49985. * @param exponent The light decay speed with the distance from the emission spot
  49986. * @param scene The scene the lights belongs to
  49987. */
  49988. function SpotLight(name, position, direction, angle, exponent, scene) {
  49989. var _this = _super.call(this, name, scene) || this;
  49990. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49991. _this._projectionTextureLightNear = 1e-6;
  49992. _this._projectionTextureLightFar = 1000.0;
  49993. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49994. _this._projectionTextureViewLightDirty = true;
  49995. _this._projectionTextureProjectionLightDirty = true;
  49996. _this._projectionTextureDirty = true;
  49997. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49998. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49999. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50000. _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);
  50001. _this.position = position;
  50002. _this.direction = direction;
  50003. _this.angle = angle;
  50004. _this.exponent = exponent;
  50005. return _this;
  50006. }
  50007. Object.defineProperty(SpotLight.prototype, "angle", {
  50008. /**
  50009. * Gets the cone angle of the spot light in Radians.
  50010. */
  50011. get: function () {
  50012. return this._angle;
  50013. },
  50014. /**
  50015. * Sets the cone angle of the spot light in Radians.
  50016. */
  50017. set: function (value) {
  50018. this._angle = value;
  50019. this._projectionTextureProjectionLightDirty = true;
  50020. this.forceProjectionMatrixCompute();
  50021. },
  50022. enumerable: true,
  50023. configurable: true
  50024. });
  50025. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50026. /**
  50027. * Allows scaling the angle of the light for shadow generation only.
  50028. */
  50029. get: function () {
  50030. return this._shadowAngleScale;
  50031. },
  50032. /**
  50033. * Allows scaling the angle of the light for shadow generation only.
  50034. */
  50035. set: function (value) {
  50036. this._shadowAngleScale = value;
  50037. this.forceProjectionMatrixCompute();
  50038. },
  50039. enumerable: true,
  50040. configurable: true
  50041. });
  50042. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50043. /**
  50044. * Allows reading the projecton texture
  50045. */
  50046. get: function () {
  50047. return this._projectionTextureMatrix;
  50048. },
  50049. enumerable: true,
  50050. configurable: true
  50051. });
  50052. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50053. /**
  50054. * Gets the near clip of the Spotlight for texture projection.
  50055. */
  50056. get: function () {
  50057. return this._projectionTextureLightNear;
  50058. },
  50059. /**
  50060. * Sets the near clip of the Spotlight for texture projection.
  50061. */
  50062. set: function (value) {
  50063. this._projectionTextureLightNear = value;
  50064. this._projectionTextureProjectionLightDirty = true;
  50065. },
  50066. enumerable: true,
  50067. configurable: true
  50068. });
  50069. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50070. /**
  50071. * Gets the far clip of the Spotlight for texture projection.
  50072. */
  50073. get: function () {
  50074. return this._projectionTextureLightFar;
  50075. },
  50076. /**
  50077. * Sets the far clip of the Spotlight for texture projection.
  50078. */
  50079. set: function (value) {
  50080. this._projectionTextureLightFar = value;
  50081. this._projectionTextureProjectionLightDirty = true;
  50082. },
  50083. enumerable: true,
  50084. configurable: true
  50085. });
  50086. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50087. /**
  50088. * Gets the Up vector of the Spotlight for texture projection.
  50089. */
  50090. get: function () {
  50091. return this._projectionTextureUpDirection;
  50092. },
  50093. /**
  50094. * Sets the Up vector of the Spotlight for texture projection.
  50095. */
  50096. set: function (value) {
  50097. this._projectionTextureUpDirection = value;
  50098. this._projectionTextureProjectionLightDirty = true;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50104. /**
  50105. * Gets the projection texture of the light.
  50106. */
  50107. get: function () {
  50108. return this._projectionTexture;
  50109. },
  50110. /**
  50111. * Sets the projection texture of the light.
  50112. */
  50113. set: function (value) {
  50114. this._projectionTexture = value;
  50115. this._projectionTextureDirty = true;
  50116. },
  50117. enumerable: true,
  50118. configurable: true
  50119. });
  50120. /**
  50121. * Returns the string "SpotLight".
  50122. * @returns the class name
  50123. */
  50124. SpotLight.prototype.getClassName = function () {
  50125. return "SpotLight";
  50126. };
  50127. /**
  50128. * Returns the integer 2.
  50129. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50130. */
  50131. SpotLight.prototype.getTypeID = function () {
  50132. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50133. };
  50134. /**
  50135. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50136. */
  50137. SpotLight.prototype._setDirection = function (value) {
  50138. _super.prototype._setDirection.call(this, value);
  50139. this._projectionTextureViewLightDirty = true;
  50140. };
  50141. /**
  50142. * Overrides the position setter to recompute the projection texture view light Matrix.
  50143. */
  50144. SpotLight.prototype._setPosition = function (value) {
  50145. _super.prototype._setPosition.call(this, value);
  50146. this._projectionTextureViewLightDirty = true;
  50147. };
  50148. /**
  50149. * 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.
  50150. * Returns the SpotLight.
  50151. */
  50152. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50153. var activeCamera = this.getScene().activeCamera;
  50154. if (!activeCamera) {
  50155. return;
  50156. }
  50157. this._shadowAngleScale = this._shadowAngleScale || 1;
  50158. var angle = this._shadowAngleScale * this._angle;
  50159. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50160. };
  50161. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50162. this._projectionTextureViewLightDirty = false;
  50163. this._projectionTextureDirty = true;
  50164. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50165. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50166. };
  50167. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50168. this._projectionTextureProjectionLightDirty = false;
  50169. this._projectionTextureDirty = true;
  50170. var light_far = this.projectionTextureLightFar;
  50171. var light_near = this.projectionTextureLightNear;
  50172. var P = light_far / (light_far - light_near);
  50173. var Q = -P * light_near;
  50174. var S = 1.0 / Math.tan(this._angle / 2.0);
  50175. var A = 1.0;
  50176. 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);
  50177. };
  50178. /**
  50179. * Main function for light texture projection matrix computing.
  50180. */
  50181. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50182. this._projectionTextureDirty = false;
  50183. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50184. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50185. };
  50186. SpotLight.prototype._buildUniformLayout = function () {
  50187. this._uniformBuffer.addUniform("vLightData", 4);
  50188. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50189. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50190. this._uniformBuffer.addUniform("vLightDirection", 3);
  50191. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50192. this._uniformBuffer.addUniform("depthValues", 2);
  50193. this._uniformBuffer.create();
  50194. };
  50195. /**
  50196. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50197. * @param effect The effect to update
  50198. * @param lightIndex The index of the light in the effect to update
  50199. * @returns The spot light
  50200. */
  50201. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50202. var normalizeDirection;
  50203. if (this.computeTransformedInformation()) {
  50204. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50205. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50206. }
  50207. else {
  50208. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50209. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50210. }
  50211. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50212. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50213. if (this._projectionTextureViewLightDirty) {
  50214. this._computeProjectionTextureViewLightMatrix();
  50215. }
  50216. if (this._projectionTextureProjectionLightDirty) {
  50217. this._computeProjectionTextureProjectionLightMatrix();
  50218. }
  50219. if (this._projectionTextureDirty) {
  50220. this._computeProjectionTextureMatrix();
  50221. }
  50222. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50223. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50224. }
  50225. return this;
  50226. };
  50227. /**
  50228. * Disposes the light and the associated resources.
  50229. */
  50230. SpotLight.prototype.dispose = function () {
  50231. _super.prototype.dispose.call(this);
  50232. if (this._projectionTexture) {
  50233. this._projectionTexture.dispose();
  50234. }
  50235. };
  50236. __decorate([
  50237. BABYLON.serialize()
  50238. ], SpotLight.prototype, "angle", null);
  50239. __decorate([
  50240. BABYLON.serialize()
  50241. ], SpotLight.prototype, "shadowAngleScale", null);
  50242. __decorate([
  50243. BABYLON.serialize()
  50244. ], SpotLight.prototype, "exponent", void 0);
  50245. __decorate([
  50246. BABYLON.serialize()
  50247. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50248. __decorate([
  50249. BABYLON.serialize()
  50250. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50251. __decorate([
  50252. BABYLON.serialize()
  50253. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50254. __decorate([
  50255. BABYLON.serializeAsTexture("projectedLightTexture")
  50256. ], SpotLight.prototype, "_projectionTexture", void 0);
  50257. return SpotLight;
  50258. }(BABYLON.ShadowLight));
  50259. BABYLON.SpotLight = SpotLight;
  50260. })(BABYLON || (BABYLON = {}));
  50261. //# sourceMappingURL=babylon.spotLight.js.map
  50262. var BABYLON;
  50263. (function (BABYLON) {
  50264. /**
  50265. * Class used to override all child animations of a given target
  50266. */
  50267. var AnimationPropertiesOverride = /** @class */ (function () {
  50268. function AnimationPropertiesOverride() {
  50269. /**
  50270. * Gets or sets a value indicating if animation blending must be used
  50271. */
  50272. this.enableBlending = false;
  50273. /**
  50274. * Gets or sets the blending speed to use when enableBlending is true
  50275. */
  50276. this.blendingSpeed = 0.01;
  50277. /**
  50278. * Gets or sets the default loop mode to use
  50279. */
  50280. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50281. }
  50282. return AnimationPropertiesOverride;
  50283. }());
  50284. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50285. })(BABYLON || (BABYLON = {}));
  50286. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50287. var BABYLON;
  50288. (function (BABYLON) {
  50289. /**
  50290. * Represents the range of an animation
  50291. */
  50292. var AnimationRange = /** @class */ (function () {
  50293. /**
  50294. * Initializes the range of an animation
  50295. * @param name The name of the animation range
  50296. * @param from The starting frame of the animation
  50297. * @param to The ending frame of the animation
  50298. */
  50299. function AnimationRange(
  50300. /**The name of the animation range**/
  50301. name,
  50302. /**The starting frame of the animation */
  50303. from,
  50304. /**The ending frame of the animation*/
  50305. to) {
  50306. this.name = name;
  50307. this.from = from;
  50308. this.to = to;
  50309. }
  50310. /**
  50311. * Makes a copy of the animation range
  50312. * @returns A copy of the animation range
  50313. */
  50314. AnimationRange.prototype.clone = function () {
  50315. return new AnimationRange(this.name, this.from, this.to);
  50316. };
  50317. return AnimationRange;
  50318. }());
  50319. BABYLON.AnimationRange = AnimationRange;
  50320. /**
  50321. * Composed of a frame, and an action function
  50322. */
  50323. var AnimationEvent = /** @class */ (function () {
  50324. /**
  50325. * Initializes the animation event
  50326. * @param frame The frame for which the event is triggered
  50327. * @param action The event to perform when triggered
  50328. * @param onlyOnce Specifies if the event should be triggered only once
  50329. */
  50330. function AnimationEvent(
  50331. /** The frame for which the event is triggered **/
  50332. frame,
  50333. /** The event to perform when triggered **/
  50334. action,
  50335. /** Specifies if the event should be triggered only once**/
  50336. onlyOnce) {
  50337. this.frame = frame;
  50338. this.action = action;
  50339. this.onlyOnce = onlyOnce;
  50340. /**
  50341. * Specifies if the animation event is done
  50342. */
  50343. this.isDone = false;
  50344. }
  50345. /** @hidden */
  50346. AnimationEvent.prototype._clone = function () {
  50347. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50348. };
  50349. return AnimationEvent;
  50350. }());
  50351. BABYLON.AnimationEvent = AnimationEvent;
  50352. /**
  50353. * A cursor which tracks a point on a path
  50354. */
  50355. var PathCursor = /** @class */ (function () {
  50356. /**
  50357. * Initializes the path cursor
  50358. * @param path The path to track
  50359. */
  50360. function PathCursor(path) {
  50361. this.path = path;
  50362. /**
  50363. * Stores path cursor callbacks for when an onchange event is triggered
  50364. */
  50365. this._onchange = new Array();
  50366. /**
  50367. * The value of the path cursor
  50368. */
  50369. this.value = 0;
  50370. /**
  50371. * The animation array of the path cursor
  50372. */
  50373. this.animations = new Array();
  50374. }
  50375. /**
  50376. * Gets the cursor point on the path
  50377. * @returns A point on the path cursor at the cursor location
  50378. */
  50379. PathCursor.prototype.getPoint = function () {
  50380. var point = this.path.getPointAtLengthPosition(this.value);
  50381. return new BABYLON.Vector3(point.x, 0, point.y);
  50382. };
  50383. /**
  50384. * Moves the cursor ahead by the step amount
  50385. * @param step The amount to move the cursor forward
  50386. * @returns This path cursor
  50387. */
  50388. PathCursor.prototype.moveAhead = function (step) {
  50389. if (step === void 0) { step = 0.002; }
  50390. this.move(step);
  50391. return this;
  50392. };
  50393. /**
  50394. * Moves the cursor behind by the step amount
  50395. * @param step The amount to move the cursor back
  50396. * @returns This path cursor
  50397. */
  50398. PathCursor.prototype.moveBack = function (step) {
  50399. if (step === void 0) { step = 0.002; }
  50400. this.move(-step);
  50401. return this;
  50402. };
  50403. /**
  50404. * Moves the cursor by the step amount
  50405. * If the step amount is greater than one, an exception is thrown
  50406. * @param step The amount to move the cursor
  50407. * @returns This path cursor
  50408. */
  50409. PathCursor.prototype.move = function (step) {
  50410. if (Math.abs(step) > 1) {
  50411. throw "step size should be less than 1.";
  50412. }
  50413. this.value += step;
  50414. this.ensureLimits();
  50415. this.raiseOnChange();
  50416. return this;
  50417. };
  50418. /**
  50419. * Ensures that the value is limited between zero and one
  50420. * @returns This path cursor
  50421. */
  50422. PathCursor.prototype.ensureLimits = function () {
  50423. while (this.value > 1) {
  50424. this.value -= 1;
  50425. }
  50426. while (this.value < 0) {
  50427. this.value += 1;
  50428. }
  50429. return this;
  50430. };
  50431. /**
  50432. * Runs onchange callbacks on change (used by the animation engine)
  50433. * @returns This path cursor
  50434. */
  50435. PathCursor.prototype.raiseOnChange = function () {
  50436. var _this = this;
  50437. this._onchange.forEach(function (f) { return f(_this); });
  50438. return this;
  50439. };
  50440. /**
  50441. * Executes a function on change
  50442. * @param f A path cursor onchange callback
  50443. * @returns This path cursor
  50444. */
  50445. PathCursor.prototype.onchange = function (f) {
  50446. this._onchange.push(f);
  50447. return this;
  50448. };
  50449. return PathCursor;
  50450. }());
  50451. BABYLON.PathCursor = PathCursor;
  50452. /**
  50453. * Enum for the animation key frame interpolation type
  50454. */
  50455. var AnimationKeyInterpolation;
  50456. (function (AnimationKeyInterpolation) {
  50457. /**
  50458. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50459. */
  50460. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50461. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50462. /**
  50463. * Class used to store any kind of animation
  50464. */
  50465. var Animation = /** @class */ (function () {
  50466. /**
  50467. * Initializes the animation
  50468. * @param name Name of the animation
  50469. * @param targetProperty Property to animate
  50470. * @param framePerSecond The frames per second of the animation
  50471. * @param dataType The data type of the animation
  50472. * @param loopMode The loop mode of the animation
  50473. * @param enableBlendings Specifies if blending should be enabled
  50474. */
  50475. function Animation(
  50476. /**Name of the animation */
  50477. name,
  50478. /**Property to animate */
  50479. targetProperty,
  50480. /**The frames per second of the animation */
  50481. framePerSecond,
  50482. /**The data type of the animation */
  50483. dataType,
  50484. /**The loop mode of the animation */
  50485. loopMode,
  50486. /**Specifies if blending should be enabled */
  50487. enableBlending) {
  50488. this.name = name;
  50489. this.targetProperty = targetProperty;
  50490. this.framePerSecond = framePerSecond;
  50491. this.dataType = dataType;
  50492. this.loopMode = loopMode;
  50493. this.enableBlending = enableBlending;
  50494. /**
  50495. * @hidden Internal use only
  50496. */
  50497. this._runtimeAnimations = new Array();
  50498. /**
  50499. * The set of event that will be linked to this animation
  50500. */
  50501. this._events = new Array();
  50502. /**
  50503. * Stores the blending speed of the animation
  50504. */
  50505. this.blendingSpeed = 0.01;
  50506. /**
  50507. * Stores the animation ranges for the animation
  50508. */
  50509. this._ranges = {};
  50510. this.targetPropertyPath = targetProperty.split(".");
  50511. this.dataType = dataType;
  50512. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50513. }
  50514. /**
  50515. * @hidden Internal use
  50516. */
  50517. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50518. var dataType = undefined;
  50519. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50520. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50521. }
  50522. else if (from instanceof BABYLON.Quaternion) {
  50523. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50524. }
  50525. else if (from instanceof BABYLON.Vector3) {
  50526. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50527. }
  50528. else if (from instanceof BABYLON.Vector2) {
  50529. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50530. }
  50531. else if (from instanceof BABYLON.Color3) {
  50532. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50533. }
  50534. else if (from instanceof BABYLON.Size) {
  50535. dataType = Animation.ANIMATIONTYPE_SIZE;
  50536. }
  50537. if (dataType == undefined) {
  50538. return null;
  50539. }
  50540. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50541. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50542. animation.setKeys(keys);
  50543. if (easingFunction !== undefined) {
  50544. animation.setEasingFunction(easingFunction);
  50545. }
  50546. return animation;
  50547. };
  50548. /**
  50549. * Sets up an animation
  50550. * @param property The property to animate
  50551. * @param animationType The animation type to apply
  50552. * @param framePerSecond The frames per second of the animation
  50553. * @param easingFunction The easing function used in the animation
  50554. * @returns The created animation
  50555. */
  50556. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50557. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50558. animation.setEasingFunction(easingFunction);
  50559. return animation;
  50560. };
  50561. /**
  50562. * Create and start an animation on a node
  50563. * @param name defines the name of the global animation that will be run on all nodes
  50564. * @param node defines the root node where the animation will take place
  50565. * @param targetProperty defines property to animate
  50566. * @param framePerSecond defines the number of frame per second yo use
  50567. * @param totalFrame defines the number of frames in total
  50568. * @param from defines the initial value
  50569. * @param to defines the final value
  50570. * @param loopMode defines which loop mode you want to use (off by default)
  50571. * @param easingFunction defines the easing function to use (linear by default)
  50572. * @param onAnimationEnd defines the callback to call when animation end
  50573. * @returns the animatable created for this animation
  50574. */
  50575. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50576. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50577. if (!animation) {
  50578. return null;
  50579. }
  50580. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50581. };
  50582. /**
  50583. * Create and start an animation on a node and its descendants
  50584. * @param name defines the name of the global animation that will be run on all nodes
  50585. * @param node defines the root node where the animation will take place
  50586. * @param 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
  50587. * @param targetProperty defines property to animate
  50588. * @param framePerSecond defines the number of frame per second to use
  50589. * @param totalFrame defines the number of frames in total
  50590. * @param from defines the initial value
  50591. * @param to defines the final value
  50592. * @param loopMode defines which loop mode you want to use (off by default)
  50593. * @param easingFunction defines the easing function to use (linear by default)
  50594. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50595. * @returns the list of animatables created for all nodes
  50596. * @example https://www.babylonjs-playground.com/#MH0VLI
  50597. */
  50598. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50599. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50600. if (!animation) {
  50601. return null;
  50602. }
  50603. var scene = node.getScene();
  50604. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50605. };
  50606. /**
  50607. * Creates a new animation, merges it with the existing animations and starts it
  50608. * @param name Name of the animation
  50609. * @param node Node which contains the scene that begins the animations
  50610. * @param targetProperty Specifies which property to animate
  50611. * @param framePerSecond The frames per second of the animation
  50612. * @param totalFrame The total number of frames
  50613. * @param from The frame at the beginning of the animation
  50614. * @param to The frame at the end of the animation
  50615. * @param loopMode Specifies the loop mode of the animation
  50616. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50617. * @param onAnimationEnd Callback to run once the animation is complete
  50618. * @returns Nullable animation
  50619. */
  50620. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50621. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50622. if (!animation) {
  50623. return null;
  50624. }
  50625. node.animations.push(animation);
  50626. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50627. };
  50628. /**
  50629. * Transition property of the Camera to the target Value
  50630. * @param property The property to transition
  50631. * @param targetValue The target Value of the property
  50632. * @param host The object where the property to animate belongs
  50633. * @param scene Scene used to run the animation
  50634. * @param frameRate Framerate (in frame/s) to use
  50635. * @param transition The transition type we want to use
  50636. * @param duration The duration of the animation, in milliseconds
  50637. * @param onAnimationEnd Callback trigger at the end of the animation
  50638. * @returns Nullable animation
  50639. */
  50640. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50641. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50642. if (duration <= 0) {
  50643. host[property] = targetValue;
  50644. if (onAnimationEnd) {
  50645. onAnimationEnd();
  50646. }
  50647. return null;
  50648. }
  50649. var endFrame = frameRate * (duration / 1000);
  50650. transition.setKeys([{
  50651. frame: 0,
  50652. value: host[property].clone ? host[property].clone() : host[property]
  50653. },
  50654. {
  50655. frame: endFrame,
  50656. value: targetValue
  50657. }]);
  50658. if (!host.animations) {
  50659. host.animations = [];
  50660. }
  50661. host.animations.push(transition);
  50662. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50663. animation.onAnimationEnd = onAnimationEnd;
  50664. return animation;
  50665. };
  50666. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50667. /**
  50668. * Return the array of runtime animations currently using this animation
  50669. */
  50670. get: function () {
  50671. return this._runtimeAnimations;
  50672. },
  50673. enumerable: true,
  50674. configurable: true
  50675. });
  50676. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50677. /**
  50678. * Specifies if any of the runtime animations are currently running
  50679. */
  50680. get: function () {
  50681. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50682. var runtimeAnimation = _a[_i];
  50683. if (!runtimeAnimation.isStopped) {
  50684. return true;
  50685. }
  50686. }
  50687. return false;
  50688. },
  50689. enumerable: true,
  50690. configurable: true
  50691. });
  50692. // Methods
  50693. /**
  50694. * Converts the animation to a string
  50695. * @param fullDetails support for multiple levels of logging within scene loading
  50696. * @returns String form of the animation
  50697. */
  50698. Animation.prototype.toString = function (fullDetails) {
  50699. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50700. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50701. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50702. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50703. if (fullDetails) {
  50704. ret += ", Ranges: {";
  50705. var first = true;
  50706. for (var name in this._ranges) {
  50707. if (first) {
  50708. ret += ", ";
  50709. first = false;
  50710. }
  50711. ret += name;
  50712. }
  50713. ret += "}";
  50714. }
  50715. return ret;
  50716. };
  50717. /**
  50718. * Add an event to this animation
  50719. * @param event Event to add
  50720. */
  50721. Animation.prototype.addEvent = function (event) {
  50722. this._events.push(event);
  50723. };
  50724. /**
  50725. * Remove all events found at the given frame
  50726. * @param frame The frame to remove events from
  50727. */
  50728. Animation.prototype.removeEvents = function (frame) {
  50729. for (var index = 0; index < this._events.length; index++) {
  50730. if (this._events[index].frame === frame) {
  50731. this._events.splice(index, 1);
  50732. index--;
  50733. }
  50734. }
  50735. };
  50736. /**
  50737. * Retrieves all the events from the animation
  50738. * @returns Events from the animation
  50739. */
  50740. Animation.prototype.getEvents = function () {
  50741. return this._events;
  50742. };
  50743. /**
  50744. * Creates an animation range
  50745. * @param name Name of the animation range
  50746. * @param from Starting frame of the animation range
  50747. * @param to Ending frame of the animation
  50748. */
  50749. Animation.prototype.createRange = function (name, from, to) {
  50750. // check name not already in use; could happen for bones after serialized
  50751. if (!this._ranges[name]) {
  50752. this._ranges[name] = new AnimationRange(name, from, to);
  50753. }
  50754. };
  50755. /**
  50756. * Deletes an animation range by name
  50757. * @param name Name of the animation range to delete
  50758. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50759. */
  50760. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50761. if (deleteFrames === void 0) { deleteFrames = true; }
  50762. var range = this._ranges[name];
  50763. if (!range) {
  50764. return;
  50765. }
  50766. if (deleteFrames) {
  50767. var from = range.from;
  50768. var to = range.to;
  50769. // this loop MUST go high to low for multiple splices to work
  50770. for (var key = this._keys.length - 1; key >= 0; key--) {
  50771. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50772. this._keys.splice(key, 1);
  50773. }
  50774. }
  50775. }
  50776. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50777. };
  50778. /**
  50779. * Gets the animation range by name, or null if not defined
  50780. * @param name Name of the animation range
  50781. * @returns Nullable animation range
  50782. */
  50783. Animation.prototype.getRange = function (name) {
  50784. return this._ranges[name];
  50785. };
  50786. /**
  50787. * Gets the key frames from the animation
  50788. * @returns The key frames of the animation
  50789. */
  50790. Animation.prototype.getKeys = function () {
  50791. return this._keys;
  50792. };
  50793. /**
  50794. * Gets the highest frame rate of the animation
  50795. * @returns Highest frame rate of the animation
  50796. */
  50797. Animation.prototype.getHighestFrame = function () {
  50798. var ret = 0;
  50799. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50800. if (ret < this._keys[key].frame) {
  50801. ret = this._keys[key].frame;
  50802. }
  50803. }
  50804. return ret;
  50805. };
  50806. /**
  50807. * Gets the easing function of the animation
  50808. * @returns Easing function of the animation
  50809. */
  50810. Animation.prototype.getEasingFunction = function () {
  50811. return this._easingFunction;
  50812. };
  50813. /**
  50814. * Sets the easing function of the animation
  50815. * @param easingFunction A custom mathematical formula for animation
  50816. */
  50817. Animation.prototype.setEasingFunction = function (easingFunction) {
  50818. this._easingFunction = easingFunction;
  50819. };
  50820. /**
  50821. * Interpolates a scalar linearly
  50822. * @param startValue Start value of the animation curve
  50823. * @param endValue End value of the animation curve
  50824. * @param gradient Scalar amount to interpolate
  50825. * @returns Interpolated scalar value
  50826. */
  50827. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50828. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50829. };
  50830. /**
  50831. * Interpolates a scalar cubically
  50832. * @param startValue Start value of the animation curve
  50833. * @param outTangent End tangent of the animation
  50834. * @param endValue End value of the animation curve
  50835. * @param inTangent Start tangent of the animation curve
  50836. * @param gradient Scalar amount to interpolate
  50837. * @returns Interpolated scalar value
  50838. */
  50839. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50840. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50841. };
  50842. /**
  50843. * Interpolates a quaternion using a spherical linear interpolation
  50844. * @param startValue Start value of the animation curve
  50845. * @param endValue End value of the animation curve
  50846. * @param gradient Scalar amount to interpolate
  50847. * @returns Interpolated quaternion value
  50848. */
  50849. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50850. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50851. };
  50852. /**
  50853. * Interpolates a quaternion cubically
  50854. * @param startValue Start value of the animation curve
  50855. * @param outTangent End tangent of the animation curve
  50856. * @param endValue End value of the animation curve
  50857. * @param inTangent Start tangent of the animation curve
  50858. * @param gradient Scalar amount to interpolate
  50859. * @returns Interpolated quaternion value
  50860. */
  50861. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50862. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50863. };
  50864. /**
  50865. * Interpolates a Vector3 linearl
  50866. * @param startValue Start value of the animation curve
  50867. * @param endValue End value of the animation curve
  50868. * @param gradient Scalar amount to interpolate
  50869. * @returns Interpolated scalar value
  50870. */
  50871. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50872. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50873. };
  50874. /**
  50875. * Interpolates a Vector3 cubically
  50876. * @param startValue Start value of the animation curve
  50877. * @param outTangent End tangent of the animation
  50878. * @param endValue End value of the animation curve
  50879. * @param inTangent Start tangent of the animation curve
  50880. * @param gradient Scalar amount to interpolate
  50881. * @returns InterpolatedVector3 value
  50882. */
  50883. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50884. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50885. };
  50886. /**
  50887. * Interpolates a Vector2 linearly
  50888. * @param startValue Start value of the animation curve
  50889. * @param endValue End value of the animation curve
  50890. * @param gradient Scalar amount to interpolate
  50891. * @returns Interpolated Vector2 value
  50892. */
  50893. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50894. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50895. };
  50896. /**
  50897. * Interpolates a Vector2 cubically
  50898. * @param startValue Start value of the animation curve
  50899. * @param outTangent End tangent of the animation
  50900. * @param endValue End value of the animation curve
  50901. * @param inTangent Start tangent of the animation curve
  50902. * @param gradient Scalar amount to interpolate
  50903. * @returns Interpolated Vector2 value
  50904. */
  50905. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50906. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50907. };
  50908. /**
  50909. * Interpolates a size linearly
  50910. * @param startValue Start value of the animation curve
  50911. * @param endValue End value of the animation curve
  50912. * @param gradient Scalar amount to interpolate
  50913. * @returns Interpolated Size value
  50914. */
  50915. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50916. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50917. };
  50918. /**
  50919. * Interpolates a Color3 linearly
  50920. * @param startValue Start value of the animation curve
  50921. * @param endValue End value of the animation curve
  50922. * @param gradient Scalar amount to interpolate
  50923. * @returns Interpolated Color3 value
  50924. */
  50925. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50926. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50927. };
  50928. /**
  50929. * @hidden Internal use only
  50930. */
  50931. Animation.prototype._getKeyValue = function (value) {
  50932. if (typeof value === "function") {
  50933. return value();
  50934. }
  50935. return value;
  50936. };
  50937. /**
  50938. * @hidden Internal use only
  50939. */
  50940. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50941. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50942. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50943. }
  50944. var keys = this.getKeys();
  50945. // Try to get a hash to find the right key
  50946. 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));
  50947. if (keys[startKeyIndex].frame >= currentFrame) {
  50948. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50949. startKeyIndex--;
  50950. }
  50951. }
  50952. for (var key = startKeyIndex; key < keys.length; key++) {
  50953. var endKey = keys[key + 1];
  50954. if (endKey.frame >= currentFrame) {
  50955. var startKey = keys[key];
  50956. var startValue = this._getKeyValue(startKey.value);
  50957. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50958. return startValue;
  50959. }
  50960. var endValue = this._getKeyValue(endKey.value);
  50961. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50962. var frameDelta = endKey.frame - startKey.frame;
  50963. // gradient : percent of currentFrame between the frame inf and the frame sup
  50964. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50965. // check for easingFunction and correction of gradient
  50966. var easingFunction = this.getEasingFunction();
  50967. if (easingFunction != null) {
  50968. gradient = easingFunction.ease(gradient);
  50969. }
  50970. switch (this.dataType) {
  50971. // Float
  50972. case Animation.ANIMATIONTYPE_FLOAT:
  50973. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50974. switch (loopMode) {
  50975. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50976. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50977. return floatValue;
  50978. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50979. return offsetValue * repeatCount + floatValue;
  50980. }
  50981. break;
  50982. // Quaternion
  50983. case Animation.ANIMATIONTYPE_QUATERNION:
  50984. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50985. switch (loopMode) {
  50986. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50987. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50988. return quatValue;
  50989. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50990. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50991. }
  50992. return quatValue;
  50993. // Vector3
  50994. case Animation.ANIMATIONTYPE_VECTOR3:
  50995. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50996. switch (loopMode) {
  50997. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50998. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50999. return vec3Value;
  51000. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51001. return vec3Value.add(offsetValue.scale(repeatCount));
  51002. }
  51003. // Vector2
  51004. case Animation.ANIMATIONTYPE_VECTOR2:
  51005. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51006. switch (loopMode) {
  51007. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51008. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51009. return vec2Value;
  51010. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51011. return vec2Value.add(offsetValue.scale(repeatCount));
  51012. }
  51013. // Size
  51014. case Animation.ANIMATIONTYPE_SIZE:
  51015. switch (loopMode) {
  51016. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51017. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51018. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51019. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51020. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51021. }
  51022. // Color3
  51023. case Animation.ANIMATIONTYPE_COLOR3:
  51024. switch (loopMode) {
  51025. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51026. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51027. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51028. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51029. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51030. }
  51031. // Matrix
  51032. case Animation.ANIMATIONTYPE_MATRIX:
  51033. switch (loopMode) {
  51034. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51035. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51036. if (Animation.AllowMatricesInterpolation) {
  51037. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51038. }
  51039. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51040. return startValue;
  51041. }
  51042. default:
  51043. break;
  51044. }
  51045. break;
  51046. }
  51047. }
  51048. return this._getKeyValue(keys[keys.length - 1].value);
  51049. };
  51050. /**
  51051. * Defines the function to use to interpolate matrices
  51052. * @param startValue defines the start matrix
  51053. * @param endValue defines the end matrix
  51054. * @param gradient defines the gradient between both matrices
  51055. * @param result defines an optional target matrix where to store the interpolation
  51056. * @returns the interpolated matrix
  51057. */
  51058. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51059. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51060. if (result) {
  51061. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51062. return result;
  51063. }
  51064. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51065. }
  51066. if (result) {
  51067. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51068. return result;
  51069. }
  51070. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51071. };
  51072. /**
  51073. * Makes a copy of the animation
  51074. * @returns Cloned animation
  51075. */
  51076. Animation.prototype.clone = function () {
  51077. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51078. clone.enableBlending = this.enableBlending;
  51079. clone.blendingSpeed = this.blendingSpeed;
  51080. if (this._keys) {
  51081. clone.setKeys(this._keys);
  51082. }
  51083. if (this._ranges) {
  51084. clone._ranges = {};
  51085. for (var name in this._ranges) {
  51086. var range = this._ranges[name];
  51087. if (!range) {
  51088. continue;
  51089. }
  51090. clone._ranges[name] = range.clone();
  51091. }
  51092. }
  51093. return clone;
  51094. };
  51095. /**
  51096. * Sets the key frames of the animation
  51097. * @param values The animation key frames to set
  51098. */
  51099. Animation.prototype.setKeys = function (values) {
  51100. this._keys = values.slice(0);
  51101. };
  51102. /**
  51103. * Serializes the animation to an object
  51104. * @returns Serialized object
  51105. */
  51106. Animation.prototype.serialize = function () {
  51107. var serializationObject = {};
  51108. serializationObject.name = this.name;
  51109. serializationObject.property = this.targetProperty;
  51110. serializationObject.framePerSecond = this.framePerSecond;
  51111. serializationObject.dataType = this.dataType;
  51112. serializationObject.loopBehavior = this.loopMode;
  51113. serializationObject.enableBlending = this.enableBlending;
  51114. serializationObject.blendingSpeed = this.blendingSpeed;
  51115. var dataType = this.dataType;
  51116. serializationObject.keys = [];
  51117. var keys = this.getKeys();
  51118. for (var index = 0; index < keys.length; index++) {
  51119. var animationKey = keys[index];
  51120. var key = {};
  51121. key.frame = animationKey.frame;
  51122. switch (dataType) {
  51123. case Animation.ANIMATIONTYPE_FLOAT:
  51124. key.values = [animationKey.value];
  51125. break;
  51126. case Animation.ANIMATIONTYPE_QUATERNION:
  51127. case Animation.ANIMATIONTYPE_MATRIX:
  51128. case Animation.ANIMATIONTYPE_VECTOR3:
  51129. case Animation.ANIMATIONTYPE_COLOR3:
  51130. key.values = animationKey.value.asArray();
  51131. break;
  51132. }
  51133. serializationObject.keys.push(key);
  51134. }
  51135. serializationObject.ranges = [];
  51136. for (var name in this._ranges) {
  51137. var source = this._ranges[name];
  51138. if (!source) {
  51139. continue;
  51140. }
  51141. var range = {};
  51142. range.name = name;
  51143. range.from = source.from;
  51144. range.to = source.to;
  51145. serializationObject.ranges.push(range);
  51146. }
  51147. return serializationObject;
  51148. };
  51149. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51150. /**
  51151. * Get the float animation type
  51152. */
  51153. get: function () {
  51154. return Animation._ANIMATIONTYPE_FLOAT;
  51155. },
  51156. enumerable: true,
  51157. configurable: true
  51158. });
  51159. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51160. /**
  51161. * Get the Vector3 animation type
  51162. */
  51163. get: function () {
  51164. return Animation._ANIMATIONTYPE_VECTOR3;
  51165. },
  51166. enumerable: true,
  51167. configurable: true
  51168. });
  51169. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51170. /**
  51171. * Get the Vectpr2 animation type
  51172. */
  51173. get: function () {
  51174. return Animation._ANIMATIONTYPE_VECTOR2;
  51175. },
  51176. enumerable: true,
  51177. configurable: true
  51178. });
  51179. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51180. /**
  51181. * Get the Size animation type
  51182. */
  51183. get: function () {
  51184. return Animation._ANIMATIONTYPE_SIZE;
  51185. },
  51186. enumerable: true,
  51187. configurable: true
  51188. });
  51189. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51190. /**
  51191. * Get the Quaternion animation type
  51192. */
  51193. get: function () {
  51194. return Animation._ANIMATIONTYPE_QUATERNION;
  51195. },
  51196. enumerable: true,
  51197. configurable: true
  51198. });
  51199. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51200. /**
  51201. * Get the Matrix animation type
  51202. */
  51203. get: function () {
  51204. return Animation._ANIMATIONTYPE_MATRIX;
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51210. /**
  51211. * Get the Color3 animation type
  51212. */
  51213. get: function () {
  51214. return Animation._ANIMATIONTYPE_COLOR3;
  51215. },
  51216. enumerable: true,
  51217. configurable: true
  51218. });
  51219. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51220. /**
  51221. * Get the Relative Loop Mode
  51222. */
  51223. get: function () {
  51224. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51230. /**
  51231. * Get the Cycle Loop Mode
  51232. */
  51233. get: function () {
  51234. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51235. },
  51236. enumerable: true,
  51237. configurable: true
  51238. });
  51239. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51240. /**
  51241. * Get the Constant Loop Mode
  51242. */
  51243. get: function () {
  51244. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. /** @hidden */
  51250. Animation._UniversalLerp = function (left, right, amount) {
  51251. var constructor = left.constructor;
  51252. if (constructor.Lerp) { // Lerp supported
  51253. return constructor.Lerp(left, right, amount);
  51254. }
  51255. else if (constructor.Slerp) { // Slerp supported
  51256. return constructor.Slerp(left, right, amount);
  51257. }
  51258. else if (left.toFixed) { // Number
  51259. return left * (1.0 - amount) + amount * right;
  51260. }
  51261. else { // Blending not supported
  51262. return right;
  51263. }
  51264. };
  51265. /**
  51266. * Parses an animation object and creates an animation
  51267. * @param parsedAnimation Parsed animation object
  51268. * @returns Animation object
  51269. */
  51270. Animation.Parse = function (parsedAnimation) {
  51271. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51272. var dataType = parsedAnimation.dataType;
  51273. var keys = [];
  51274. var data;
  51275. var index;
  51276. if (parsedAnimation.enableBlending) {
  51277. animation.enableBlending = parsedAnimation.enableBlending;
  51278. }
  51279. if (parsedAnimation.blendingSpeed) {
  51280. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51281. }
  51282. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51283. var key = parsedAnimation.keys[index];
  51284. var inTangent;
  51285. var outTangent;
  51286. switch (dataType) {
  51287. case Animation.ANIMATIONTYPE_FLOAT:
  51288. data = key.values[0];
  51289. if (key.values.length >= 1) {
  51290. inTangent = key.values[1];
  51291. }
  51292. if (key.values.length >= 2) {
  51293. outTangent = key.values[2];
  51294. }
  51295. break;
  51296. case Animation.ANIMATIONTYPE_QUATERNION:
  51297. data = BABYLON.Quaternion.FromArray(key.values);
  51298. if (key.values.length >= 8) {
  51299. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51300. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51301. inTangent = _inTangent;
  51302. }
  51303. }
  51304. if (key.values.length >= 12) {
  51305. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51306. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51307. outTangent = _outTangent;
  51308. }
  51309. }
  51310. break;
  51311. case Animation.ANIMATIONTYPE_MATRIX:
  51312. data = BABYLON.Matrix.FromArray(key.values);
  51313. break;
  51314. case Animation.ANIMATIONTYPE_COLOR3:
  51315. data = BABYLON.Color3.FromArray(key.values);
  51316. break;
  51317. case Animation.ANIMATIONTYPE_VECTOR3:
  51318. default:
  51319. data = BABYLON.Vector3.FromArray(key.values);
  51320. break;
  51321. }
  51322. var keyData = {};
  51323. keyData.frame = key.frame;
  51324. keyData.value = data;
  51325. if (inTangent != undefined) {
  51326. keyData.inTangent = inTangent;
  51327. }
  51328. if (outTangent != undefined) {
  51329. keyData.outTangent = outTangent;
  51330. }
  51331. keys.push(keyData);
  51332. }
  51333. animation.setKeys(keys);
  51334. if (parsedAnimation.ranges) {
  51335. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51336. data = parsedAnimation.ranges[index];
  51337. animation.createRange(data.name, data.from, data.to);
  51338. }
  51339. }
  51340. return animation;
  51341. };
  51342. /**
  51343. * Appends the serialized animations from the source animations
  51344. * @param source Source containing the animations
  51345. * @param destination Target to store the animations
  51346. */
  51347. Animation.AppendSerializedAnimations = function (source, destination) {
  51348. if (source.animations) {
  51349. destination.animations = [];
  51350. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51351. var animation = source.animations[animationIndex];
  51352. destination.animations.push(animation.serialize());
  51353. }
  51354. }
  51355. };
  51356. /**
  51357. * Use matrix interpolation instead of using direct key value when animating matrices
  51358. */
  51359. Animation.AllowMatricesInterpolation = false;
  51360. /**
  51361. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51362. */
  51363. Animation.AllowMatrixDecomposeForInterpolation = true;
  51364. // Statics
  51365. /**
  51366. * Float animation type
  51367. */
  51368. Animation._ANIMATIONTYPE_FLOAT = 0;
  51369. /**
  51370. * Vector3 animation type
  51371. */
  51372. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51373. /**
  51374. * Quaternion animation type
  51375. */
  51376. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51377. /**
  51378. * Matrix animation type
  51379. */
  51380. Animation._ANIMATIONTYPE_MATRIX = 3;
  51381. /**
  51382. * Color3 animation type
  51383. */
  51384. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51385. /**
  51386. * Vector2 animation type
  51387. */
  51388. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51389. /**
  51390. * Size animation type
  51391. */
  51392. Animation._ANIMATIONTYPE_SIZE = 6;
  51393. /**
  51394. * Relative Loop Mode
  51395. */
  51396. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51397. /**
  51398. * Cycle Loop Mode
  51399. */
  51400. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51401. /**
  51402. * Constant Loop Mode
  51403. */
  51404. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51405. return Animation;
  51406. }());
  51407. BABYLON.Animation = Animation;
  51408. })(BABYLON || (BABYLON = {}));
  51409. //# sourceMappingURL=babylon.animation.js.map
  51410. var BABYLON;
  51411. (function (BABYLON) {
  51412. /**
  51413. * This class defines the direct association between an animation and a target
  51414. */
  51415. var TargetedAnimation = /** @class */ (function () {
  51416. function TargetedAnimation() {
  51417. }
  51418. return TargetedAnimation;
  51419. }());
  51420. BABYLON.TargetedAnimation = TargetedAnimation;
  51421. /**
  51422. * Use this class to create coordinated animations on multiple targets
  51423. */
  51424. var AnimationGroup = /** @class */ (function () {
  51425. function AnimationGroup(name, scene) {
  51426. if (scene === void 0) { scene = null; }
  51427. this.name = name;
  51428. this._targetedAnimations = new Array();
  51429. this._animatables = new Array();
  51430. this._from = Number.MAX_VALUE;
  51431. this._to = -Number.MAX_VALUE;
  51432. this._speedRatio = 1;
  51433. this.onAnimationEndObservable = new BABYLON.Observable();
  51434. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51435. this._scene.animationGroups.push(this);
  51436. }
  51437. Object.defineProperty(AnimationGroup.prototype, "from", {
  51438. /**
  51439. * Gets the first frame
  51440. */
  51441. get: function () {
  51442. return this._from;
  51443. },
  51444. enumerable: true,
  51445. configurable: true
  51446. });
  51447. Object.defineProperty(AnimationGroup.prototype, "to", {
  51448. /**
  51449. * Gets the last frame
  51450. */
  51451. get: function () {
  51452. return this._to;
  51453. },
  51454. enumerable: true,
  51455. configurable: true
  51456. });
  51457. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51458. /**
  51459. * Define if the animations are started
  51460. */
  51461. get: function () {
  51462. return this._isStarted;
  51463. },
  51464. enumerable: true,
  51465. configurable: true
  51466. });
  51467. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51468. /**
  51469. * Gets or sets the speed ratio to use for all animations
  51470. */
  51471. get: function () {
  51472. return this._speedRatio;
  51473. },
  51474. /**
  51475. * Gets or sets the speed ratio to use for all animations
  51476. */
  51477. set: function (value) {
  51478. if (this._speedRatio === value) {
  51479. return;
  51480. }
  51481. this._speedRatio = value;
  51482. for (var index = 0; index < this._animatables.length; index++) {
  51483. var animatable = this._animatables[index];
  51484. animatable.speedRatio = this._speedRatio;
  51485. }
  51486. },
  51487. enumerable: true,
  51488. configurable: true
  51489. });
  51490. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51491. /**
  51492. * Gets the targeted animations for this animation group
  51493. */
  51494. get: function () {
  51495. return this._targetedAnimations;
  51496. },
  51497. enumerable: true,
  51498. configurable: true
  51499. });
  51500. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51501. /**
  51502. * returning the list of animatables controlled by this animation group.
  51503. */
  51504. get: function () {
  51505. return this._animatables;
  51506. },
  51507. enumerable: true,
  51508. configurable: true
  51509. });
  51510. /**
  51511. * Add an animation (with its target) in the group
  51512. * @param animation defines the animation we want to add
  51513. * @param target defines the target of the animation
  51514. * @returns the {BABYLON.TargetedAnimation} object
  51515. */
  51516. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51517. var targetedAnimation = {
  51518. animation: animation,
  51519. target: target
  51520. };
  51521. var keys = animation.getKeys();
  51522. if (this._from > keys[0].frame) {
  51523. this._from = keys[0].frame;
  51524. }
  51525. if (this._to < keys[keys.length - 1].frame) {
  51526. this._to = keys[keys.length - 1].frame;
  51527. }
  51528. this._targetedAnimations.push(targetedAnimation);
  51529. return targetedAnimation;
  51530. };
  51531. /**
  51532. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51533. * It can add constant keys at begin or end
  51534. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51535. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51536. */
  51537. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51538. if (beginFrame === void 0) { beginFrame = null; }
  51539. if (endFrame === void 0) { endFrame = null; }
  51540. if (beginFrame == null)
  51541. beginFrame = this._from;
  51542. if (endFrame == null)
  51543. endFrame = this._to;
  51544. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51545. var targetedAnimation = this._targetedAnimations[index];
  51546. var keys = targetedAnimation.animation.getKeys();
  51547. var startKey = keys[0];
  51548. var endKey = keys[keys.length - 1];
  51549. if (startKey.frame > beginFrame) {
  51550. var newKey = {
  51551. frame: beginFrame,
  51552. value: startKey.value,
  51553. inTangent: startKey.inTangent,
  51554. outTangent: startKey.outTangent,
  51555. interpolation: startKey.interpolation
  51556. };
  51557. keys.splice(0, 0, newKey);
  51558. }
  51559. if (endKey.frame < endFrame) {
  51560. var newKey = {
  51561. frame: endFrame,
  51562. value: endKey.value,
  51563. inTangent: endKey.outTangent,
  51564. outTangent: endKey.outTangent,
  51565. interpolation: endKey.interpolation
  51566. };
  51567. keys.push(newKey);
  51568. }
  51569. }
  51570. this._from = beginFrame;
  51571. this._to = endFrame;
  51572. return this;
  51573. };
  51574. /**
  51575. * Start all animations on given targets
  51576. * @param loop defines if animations must loop
  51577. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51578. * @param from defines the from key (optional)
  51579. * @param to defines the to key (optional)
  51580. * @returns the current animation group
  51581. */
  51582. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51583. var _this = this;
  51584. if (loop === void 0) { loop = false; }
  51585. if (speedRatio === void 0) { speedRatio = 1; }
  51586. if (this._isStarted || this._targetedAnimations.length === 0) {
  51587. return this;
  51588. }
  51589. var _loop_1 = function (targetedAnimation) {
  51590. 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 () {
  51591. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51592. }));
  51593. };
  51594. var this_1 = this;
  51595. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51596. var targetedAnimation = _a[_i];
  51597. _loop_1(targetedAnimation);
  51598. }
  51599. this._speedRatio = speedRatio;
  51600. this._isStarted = true;
  51601. return this;
  51602. };
  51603. /**
  51604. * Pause all animations
  51605. */
  51606. AnimationGroup.prototype.pause = function () {
  51607. if (!this._isStarted) {
  51608. return this;
  51609. }
  51610. for (var index = 0; index < this._animatables.length; index++) {
  51611. var animatable = this._animatables[index];
  51612. animatable.pause();
  51613. }
  51614. return this;
  51615. };
  51616. /**
  51617. * Play all animations to initial state
  51618. * This function will start() the animations if they were not started or will restart() them if they were paused
  51619. * @param loop defines if animations must loop
  51620. */
  51621. AnimationGroup.prototype.play = function (loop) {
  51622. if (this.isStarted) {
  51623. if (loop !== undefined) {
  51624. for (var index = 0; index < this._animatables.length; index++) {
  51625. var animatable = this._animatables[index];
  51626. animatable.loopAnimation = loop;
  51627. }
  51628. }
  51629. this.restart();
  51630. }
  51631. else {
  51632. this.start(loop, this._speedRatio);
  51633. }
  51634. return this;
  51635. };
  51636. /**
  51637. * Reset all animations to initial state
  51638. */
  51639. AnimationGroup.prototype.reset = function () {
  51640. if (!this._isStarted) {
  51641. return this;
  51642. }
  51643. for (var index = 0; index < this._animatables.length; index++) {
  51644. var animatable = this._animatables[index];
  51645. animatable.reset();
  51646. }
  51647. return this;
  51648. };
  51649. /**
  51650. * Restart animations from key 0
  51651. */
  51652. AnimationGroup.prototype.restart = function () {
  51653. if (!this._isStarted) {
  51654. return this;
  51655. }
  51656. for (var index = 0; index < this._animatables.length; index++) {
  51657. var animatable = this._animatables[index];
  51658. animatable.restart();
  51659. }
  51660. return this;
  51661. };
  51662. /**
  51663. * Stop all animations
  51664. */
  51665. AnimationGroup.prototype.stop = function () {
  51666. if (!this._isStarted) {
  51667. return this;
  51668. }
  51669. for (var index = 0; index < this._animatables.length; index++) {
  51670. var animatable = this._animatables[index];
  51671. animatable.stop();
  51672. }
  51673. this._isStarted = false;
  51674. return this;
  51675. };
  51676. /**
  51677. * Set animation weight for all animatables
  51678. * @param weight defines the weight to use
  51679. * @return the animationGroup
  51680. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51681. */
  51682. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51683. for (var index = 0; index < this._animatables.length; index++) {
  51684. var animatable = this._animatables[index];
  51685. animatable.weight = weight;
  51686. }
  51687. return this;
  51688. };
  51689. /**
  51690. * Synchronize and normalize all animatables with a source animatable
  51691. * @param root defines the root animatable to synchronize with
  51692. * @return the animationGroup
  51693. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51694. */
  51695. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51696. for (var index = 0; index < this._animatables.length; index++) {
  51697. var animatable = this._animatables[index];
  51698. animatable.syncWith(root);
  51699. }
  51700. return this;
  51701. };
  51702. /**
  51703. * Goes to a specific frame in this animation group
  51704. * @param frame the frame number to go to
  51705. * @return the animationGroup
  51706. */
  51707. AnimationGroup.prototype.goToFrame = function (frame) {
  51708. if (!this._isStarted) {
  51709. return this;
  51710. }
  51711. for (var index = 0; index < this._animatables.length; index++) {
  51712. var animatable = this._animatables[index];
  51713. animatable.goToFrame(frame);
  51714. }
  51715. return this;
  51716. };
  51717. /**
  51718. * Dispose all associated resources
  51719. */
  51720. AnimationGroup.prototype.dispose = function () {
  51721. this._targetedAnimations = [];
  51722. this._animatables = [];
  51723. var index = this._scene.animationGroups.indexOf(this);
  51724. if (index > -1) {
  51725. this._scene.animationGroups.splice(index, 1);
  51726. }
  51727. };
  51728. return AnimationGroup;
  51729. }());
  51730. BABYLON.AnimationGroup = AnimationGroup;
  51731. })(BABYLON || (BABYLON = {}));
  51732. //# sourceMappingURL=babylon.animationGroup.js.map
  51733. var BABYLON;
  51734. (function (BABYLON) {
  51735. /**
  51736. * Defines a runtime animation
  51737. */
  51738. var RuntimeAnimation = /** @class */ (function () {
  51739. /**
  51740. * Create a new RuntimeAnimation object
  51741. * @param target defines the target of the animation
  51742. * @param animation defines the source animation object
  51743. * @param scene defines the hosting scene
  51744. * @param host defines the initiating Animatable
  51745. */
  51746. function RuntimeAnimation(target, animation, scene, host) {
  51747. var _this = this;
  51748. this._events = new Array();
  51749. /**
  51750. * The current frame of the runtime animation
  51751. */
  51752. this._currentFrame = 0;
  51753. /**
  51754. * The original value of the runtime animation
  51755. */
  51756. this._originalValue = new Array();
  51757. /**
  51758. * The offsets cache of the runtime animation
  51759. */
  51760. this._offsetsCache = {};
  51761. /**
  51762. * The high limits cache of the runtime animation
  51763. */
  51764. this._highLimitsCache = {};
  51765. /**
  51766. * Specifies if the runtime animation has been stopped
  51767. */
  51768. this._stopped = false;
  51769. /**
  51770. * The blending factor of the runtime animation
  51771. */
  51772. this._blendingFactor = 0;
  51773. /**
  51774. * The target path of the runtime animation
  51775. */
  51776. this._targetPath = "";
  51777. /**
  51778. * The weight of the runtime animation
  51779. */
  51780. this._weight = 1.0;
  51781. /**
  51782. * The ratio offset of the runtime animation
  51783. */
  51784. this._ratioOffset = 0;
  51785. /**
  51786. * The previous delay of the runtime animation
  51787. */
  51788. this._previousDelay = 0;
  51789. /**
  51790. * The previous ratio of the runtime animation
  51791. */
  51792. this._previousRatio = 0;
  51793. this._animation = animation;
  51794. this._target = target;
  51795. this._scene = scene;
  51796. this._host = host;
  51797. animation._runtimeAnimations.push(this);
  51798. // Cloning events locally
  51799. var events = animation.getEvents();
  51800. if (events && events.length > 0) {
  51801. events.forEach(function (e) {
  51802. _this._events.push(e._clone());
  51803. });
  51804. }
  51805. }
  51806. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51807. /**
  51808. * Gets the current frame of the runtime animation
  51809. */
  51810. get: function () {
  51811. return this._currentFrame;
  51812. },
  51813. enumerable: true,
  51814. configurable: true
  51815. });
  51816. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51817. /**
  51818. * Gets the weight of the runtime animation
  51819. */
  51820. get: function () {
  51821. return this._weight;
  51822. },
  51823. enumerable: true,
  51824. configurable: true
  51825. });
  51826. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51827. /**
  51828. * Gets the current value of the runtime animation
  51829. */
  51830. get: function () {
  51831. return this._currentValue;
  51832. },
  51833. enumerable: true,
  51834. configurable: true
  51835. });
  51836. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51837. /**
  51838. * Gets the target path of the runtime animation
  51839. */
  51840. get: function () {
  51841. return this._targetPath;
  51842. },
  51843. enumerable: true,
  51844. configurable: true
  51845. });
  51846. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51847. /**
  51848. * Gets the actual target of the runtime animation
  51849. */
  51850. get: function () {
  51851. return this._activeTarget;
  51852. },
  51853. enumerable: true,
  51854. configurable: true
  51855. });
  51856. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51857. /**
  51858. * Gets the animation from the runtime animation
  51859. */
  51860. get: function () {
  51861. return this._animation;
  51862. },
  51863. enumerable: true,
  51864. configurable: true
  51865. });
  51866. /**
  51867. * Resets the runtime animation to the beginning
  51868. * @param restoreOriginal defines whether to restore the target property to the original value
  51869. */
  51870. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51871. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51872. if (restoreOriginal) {
  51873. if (this._target instanceof Array) {
  51874. var index = 0;
  51875. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51876. var target = _a[_i];
  51877. if (this._originalValue[index] !== undefined) {
  51878. this._setValue(target, this._originalValue[index], -1);
  51879. }
  51880. index++;
  51881. }
  51882. }
  51883. else {
  51884. if (this._originalValue[0] !== undefined) {
  51885. this._setValue(this._target, this._originalValue[0], -1);
  51886. }
  51887. }
  51888. }
  51889. this._offsetsCache = {};
  51890. this._highLimitsCache = {};
  51891. this._currentFrame = 0;
  51892. this._blendingFactor = 0;
  51893. this._originalValue = new Array();
  51894. // Events
  51895. for (var index = 0; index < this._events.length; index++) {
  51896. this._events[index].isDone = false;
  51897. }
  51898. };
  51899. /**
  51900. * Specifies if the runtime animation is stopped
  51901. * @returns Boolean specifying if the runtime animation is stopped
  51902. */
  51903. RuntimeAnimation.prototype.isStopped = function () {
  51904. return this._stopped;
  51905. };
  51906. /**
  51907. * Disposes of the runtime animation
  51908. */
  51909. RuntimeAnimation.prototype.dispose = function () {
  51910. var index = this._animation.runtimeAnimations.indexOf(this);
  51911. if (index > -1) {
  51912. this._animation.runtimeAnimations.splice(index, 1);
  51913. }
  51914. };
  51915. /**
  51916. * Interpolates the animation from the current frame
  51917. * @param currentFrame The frame to interpolate the animation to
  51918. * @param repeatCount The number of times that the animation should loop
  51919. * @param loopMode The type of looping mode to use
  51920. * @param offsetValue Animation offset value
  51921. * @param highLimitValue The high limit value
  51922. * @returns The interpolated value
  51923. */
  51924. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51925. this._currentFrame = currentFrame;
  51926. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51927. this._workValue = BABYLON.Matrix.Zero();
  51928. }
  51929. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51930. };
  51931. /**
  51932. * Apply the interpolated value to the target
  51933. * @param currentValue defines the value computed by the animation
  51934. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51935. */
  51936. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51937. if (weight === void 0) { weight = 1.0; }
  51938. if (this._target instanceof Array) {
  51939. var index = 0;
  51940. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51941. var target = _a[_i];
  51942. this._setValue(target, currentValue, weight, index);
  51943. index++;
  51944. }
  51945. }
  51946. else {
  51947. this._setValue(this._target, currentValue, weight);
  51948. }
  51949. };
  51950. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51951. if (targetIndex === void 0) { targetIndex = 0; }
  51952. // Set value
  51953. var path;
  51954. var destination;
  51955. var targetPropertyPath = this._animation.targetPropertyPath;
  51956. if (targetPropertyPath.length > 1) {
  51957. var property = target[targetPropertyPath[0]];
  51958. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51959. property = property[targetPropertyPath[index]];
  51960. }
  51961. path = targetPropertyPath[targetPropertyPath.length - 1];
  51962. destination = property;
  51963. }
  51964. else {
  51965. path = targetPropertyPath[0];
  51966. destination = target;
  51967. }
  51968. this._targetPath = path;
  51969. this._activeTarget = destination;
  51970. this._weight = weight;
  51971. if (this._originalValue[targetIndex] === undefined) {
  51972. var originalValue = void 0;
  51973. if (destination.getRestPose && path === "_matrix") { // For bones
  51974. originalValue = destination.getRestPose();
  51975. }
  51976. else {
  51977. originalValue = destination[path];
  51978. }
  51979. if (originalValue && originalValue.clone) {
  51980. this._originalValue[targetIndex] = originalValue.clone();
  51981. }
  51982. else {
  51983. this._originalValue[targetIndex] = originalValue;
  51984. }
  51985. }
  51986. // Blending
  51987. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51988. if (enableBlending && this._blendingFactor <= 1.0) {
  51989. if (!this._originalBlendValue) {
  51990. var originalValue = destination[path];
  51991. if (originalValue.clone) {
  51992. this._originalBlendValue = originalValue.clone();
  51993. }
  51994. else {
  51995. this._originalBlendValue = originalValue;
  51996. }
  51997. }
  51998. if (this._originalBlendValue.m) { // Matrix
  51999. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52000. if (this._currentValue) {
  52001. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52002. }
  52003. else {
  52004. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52005. }
  52006. }
  52007. else {
  52008. if (this._currentValue) {
  52009. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52010. }
  52011. else {
  52012. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52013. }
  52014. }
  52015. }
  52016. else {
  52017. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52018. }
  52019. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52020. this._blendingFactor += blendingSpeed;
  52021. }
  52022. else {
  52023. this._currentValue = currentValue;
  52024. }
  52025. if (weight !== -1.0) {
  52026. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52027. }
  52028. else {
  52029. destination[path] = this._currentValue;
  52030. }
  52031. if (target.markAsDirty) {
  52032. target.markAsDirty(this._animation.targetProperty);
  52033. }
  52034. };
  52035. /**
  52036. * Gets the loop pmode of the runtime animation
  52037. * @returns Loop Mode
  52038. */
  52039. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52040. if (this._target && this._target.animationPropertiesOverride) {
  52041. return this._target.animationPropertiesOverride.loopMode;
  52042. }
  52043. return this._animation.loopMode;
  52044. };
  52045. /**
  52046. * Move the current animation to a given frame
  52047. * @param frame defines the frame to move to
  52048. */
  52049. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52050. var keys = this._animation.getKeys();
  52051. if (frame < keys[0].frame) {
  52052. frame = keys[0].frame;
  52053. }
  52054. else if (frame > keys[keys.length - 1].frame) {
  52055. frame = keys[keys.length - 1].frame;
  52056. }
  52057. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52058. this.setValue(currentValue, -1);
  52059. };
  52060. /**
  52061. * @hidden Internal use only
  52062. */
  52063. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52064. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52065. this._ratioOffset = this._previousRatio - newRatio;
  52066. };
  52067. /**
  52068. * Execute the current animation
  52069. * @param delay defines the delay to add to the current frame
  52070. * @param from defines the lower bound of the animation range
  52071. * @param to defines the upper bound of the animation range
  52072. * @param loop defines if the current animation must loop
  52073. * @param speedRatio defines the current speed ratio
  52074. * @param weight defines the weight of the animation (default is -1 so no weight)
  52075. * @returns a boolean indicating if the animation has ended
  52076. */
  52077. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52078. if (weight === void 0) { weight = -1.0; }
  52079. var targetPropertyPath = this._animation.targetPropertyPath;
  52080. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52081. this._stopped = true;
  52082. return false;
  52083. }
  52084. var returnValue = true;
  52085. var keys = this._animation.getKeys();
  52086. // Adding a start key at frame 0 if missing
  52087. if (keys[0].frame !== 0) {
  52088. var newKey = { frame: 0, value: keys[0].value };
  52089. keys.splice(0, 0, newKey);
  52090. }
  52091. // Check limits
  52092. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52093. from = keys[0].frame;
  52094. }
  52095. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52096. to = keys[keys.length - 1].frame;
  52097. }
  52098. //to and from cannot be the same key
  52099. if (from === to) {
  52100. if (from > keys[0].frame) {
  52101. from--;
  52102. }
  52103. else if (to < keys[keys.length - 1].frame) {
  52104. to++;
  52105. }
  52106. }
  52107. // Compute ratio
  52108. var range = to - from;
  52109. var offsetValue;
  52110. // ratio represents the frame delta between from and to
  52111. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52112. var highLimitValue = 0;
  52113. this._previousDelay = delay;
  52114. this._previousRatio = ratio;
  52115. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52116. returnValue = false;
  52117. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52118. }
  52119. else {
  52120. // Get max value if required
  52121. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52122. var keyOffset = to.toString() + from.toString();
  52123. if (!this._offsetsCache[keyOffset]) {
  52124. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52125. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52126. switch (this._animation.dataType) {
  52127. // Float
  52128. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52129. this._offsetsCache[keyOffset] = toValue - fromValue;
  52130. break;
  52131. // Quaternion
  52132. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52133. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52134. break;
  52135. // Vector3
  52136. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52138. // Vector2
  52139. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52140. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52141. // Size
  52142. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52144. // Color3
  52145. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52146. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52147. default:
  52148. break;
  52149. }
  52150. this._highLimitsCache[keyOffset] = toValue;
  52151. }
  52152. highLimitValue = this._highLimitsCache[keyOffset];
  52153. offsetValue = this._offsetsCache[keyOffset];
  52154. }
  52155. }
  52156. if (offsetValue === undefined) {
  52157. switch (this._animation.dataType) {
  52158. // Float
  52159. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52160. offsetValue = 0;
  52161. break;
  52162. // Quaternion
  52163. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52164. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52165. break;
  52166. // Vector3
  52167. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52168. offsetValue = BABYLON.Vector3.Zero();
  52169. break;
  52170. // Vector2
  52171. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52172. offsetValue = BABYLON.Vector2.Zero();
  52173. break;
  52174. // Size
  52175. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52176. offsetValue = BABYLON.Size.Zero();
  52177. break;
  52178. // Color3
  52179. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52180. offsetValue = BABYLON.Color3.Black();
  52181. }
  52182. }
  52183. // Compute value
  52184. var repeatCount = (ratio / range) >> 0;
  52185. var currentFrame = returnValue ? from + ratio % range : to;
  52186. // Need to normalize?
  52187. if (this._host && this._host.syncRoot) {
  52188. var syncRoot = this._host.syncRoot;
  52189. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52190. currentFrame = from + (to - from) * hostNormalizedFrame;
  52191. }
  52192. // Reset events if looping
  52193. var events = this._events;
  52194. if (range > 0 && this.currentFrame > currentFrame ||
  52195. range < 0 && this.currentFrame < currentFrame) {
  52196. // Need to reset animation events
  52197. for (var index = 0; index < events.length; index++) {
  52198. if (!events[index].onlyOnce) {
  52199. // reset event, the animation is looping
  52200. events[index].isDone = false;
  52201. }
  52202. }
  52203. }
  52204. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52205. // Set value
  52206. this.setValue(currentValue, weight);
  52207. // Check events
  52208. for (var index = 0; index < events.length; index++) {
  52209. // Make sure current frame has passed event frame and that event frame is within the current range
  52210. // Also, handle both forward and reverse animations
  52211. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52212. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52213. var event = events[index];
  52214. if (!event.isDone) {
  52215. // If event should be done only once, remove it.
  52216. if (event.onlyOnce) {
  52217. events.splice(index, 1);
  52218. index--;
  52219. }
  52220. event.isDone = true;
  52221. event.action();
  52222. } // Don't do anything if the event has already be done.
  52223. }
  52224. }
  52225. if (!returnValue) {
  52226. this._stopped = true;
  52227. }
  52228. return returnValue;
  52229. };
  52230. return RuntimeAnimation;
  52231. }());
  52232. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52233. })(BABYLON || (BABYLON = {}));
  52234. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52235. var BABYLON;
  52236. (function (BABYLON) {
  52237. var Animatable = /** @class */ (function () {
  52238. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52239. if (fromFrame === void 0) { fromFrame = 0; }
  52240. if (toFrame === void 0) { toFrame = 100; }
  52241. if (loopAnimation === void 0) { loopAnimation = false; }
  52242. if (speedRatio === void 0) { speedRatio = 1.0; }
  52243. this.target = target;
  52244. this.fromFrame = fromFrame;
  52245. this.toFrame = toFrame;
  52246. this.loopAnimation = loopAnimation;
  52247. this.onAnimationEnd = onAnimationEnd;
  52248. this._localDelayOffset = null;
  52249. this._pausedDelay = null;
  52250. this._runtimeAnimations = new Array();
  52251. this._paused = false;
  52252. this._speedRatio = 1;
  52253. this._weight = -1.0;
  52254. this.animationStarted = false;
  52255. this._scene = scene;
  52256. if (animations) {
  52257. this.appendAnimations(target, animations);
  52258. }
  52259. this._speedRatio = speedRatio;
  52260. scene._activeAnimatables.push(this);
  52261. }
  52262. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52263. /**
  52264. * Gets the root Animatable used to synchronize and normalize animations
  52265. */
  52266. get: function () {
  52267. return this._syncRoot;
  52268. },
  52269. enumerable: true,
  52270. configurable: true
  52271. });
  52272. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52273. /**
  52274. * Gets the current frame of the first RuntimeAnimation
  52275. * Used to synchronize Animatables
  52276. */
  52277. get: function () {
  52278. if (this._runtimeAnimations.length === 0) {
  52279. return 0;
  52280. }
  52281. return this._runtimeAnimations[0].currentFrame;
  52282. },
  52283. enumerable: true,
  52284. configurable: true
  52285. });
  52286. Object.defineProperty(Animatable.prototype, "weight", {
  52287. /**
  52288. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52289. */
  52290. get: function () {
  52291. return this._weight;
  52292. },
  52293. set: function (value) {
  52294. if (value === -1) { // -1 is ok and means no weight
  52295. this._weight = -1;
  52296. return;
  52297. }
  52298. // Else weight must be in [0, 1] range
  52299. this._weight = Math.min(Math.max(value, 0), 1.0);
  52300. },
  52301. enumerable: true,
  52302. configurable: true
  52303. });
  52304. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52305. /**
  52306. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52307. */
  52308. get: function () {
  52309. return this._speedRatio;
  52310. },
  52311. set: function (value) {
  52312. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52313. var animation = this._runtimeAnimations[index];
  52314. animation._prepareForSpeedRatioChange(value);
  52315. }
  52316. this._speedRatio = value;
  52317. },
  52318. enumerable: true,
  52319. configurable: true
  52320. });
  52321. // Methods
  52322. /**
  52323. * Synchronize and normalize current Animatable with a source Animatable
  52324. * This is useful when using animation weights and when animations are not of the same length
  52325. * @param root defines the root Animatable to synchronize with
  52326. * @returns the current Animatable
  52327. */
  52328. Animatable.prototype.syncWith = function (root) {
  52329. this._syncRoot = root;
  52330. if (root) {
  52331. // Make sure this animatable will animate after the root
  52332. var index = this._scene._activeAnimatables.indexOf(this);
  52333. if (index > -1) {
  52334. this._scene._activeAnimatables.splice(index, 1);
  52335. this._scene._activeAnimatables.push(this);
  52336. }
  52337. }
  52338. return this;
  52339. };
  52340. Animatable.prototype.getAnimations = function () {
  52341. return this._runtimeAnimations;
  52342. };
  52343. Animatable.prototype.appendAnimations = function (target, animations) {
  52344. for (var index = 0; index < animations.length; index++) {
  52345. var animation = animations[index];
  52346. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52347. }
  52348. };
  52349. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52350. var runtimeAnimations = this._runtimeAnimations;
  52351. for (var index = 0; index < runtimeAnimations.length; index++) {
  52352. if (runtimeAnimations[index].animation.targetProperty === property) {
  52353. return runtimeAnimations[index].animation;
  52354. }
  52355. }
  52356. return null;
  52357. };
  52358. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52359. var runtimeAnimations = this._runtimeAnimations;
  52360. for (var index = 0; index < runtimeAnimations.length; index++) {
  52361. if (runtimeAnimations[index].animation.targetProperty === property) {
  52362. return runtimeAnimations[index];
  52363. }
  52364. }
  52365. return null;
  52366. };
  52367. Animatable.prototype.reset = function () {
  52368. var runtimeAnimations = this._runtimeAnimations;
  52369. for (var index = 0; index < runtimeAnimations.length; index++) {
  52370. runtimeAnimations[index].reset(true);
  52371. }
  52372. this._localDelayOffset = null;
  52373. this._pausedDelay = null;
  52374. };
  52375. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52376. var runtimeAnimations = this._runtimeAnimations;
  52377. for (var index = 0; index < runtimeAnimations.length; index++) {
  52378. runtimeAnimations[index].animation.enableBlending = true;
  52379. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52380. }
  52381. };
  52382. Animatable.prototype.disableBlending = function () {
  52383. var runtimeAnimations = this._runtimeAnimations;
  52384. for (var index = 0; index < runtimeAnimations.length; index++) {
  52385. runtimeAnimations[index].animation.enableBlending = false;
  52386. }
  52387. };
  52388. Animatable.prototype.goToFrame = function (frame) {
  52389. var runtimeAnimations = this._runtimeAnimations;
  52390. if (runtimeAnimations[0]) {
  52391. var fps = runtimeAnimations[0].animation.framePerSecond;
  52392. var currentFrame = runtimeAnimations[0].currentFrame;
  52393. var adjustTime = frame - currentFrame;
  52394. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52395. if (this._localDelayOffset === null) {
  52396. this._localDelayOffset = 0;
  52397. }
  52398. this._localDelayOffset -= delay;
  52399. }
  52400. for (var index = 0; index < runtimeAnimations.length; index++) {
  52401. runtimeAnimations[index].goToFrame(frame);
  52402. }
  52403. };
  52404. Animatable.prototype.pause = function () {
  52405. if (this._paused) {
  52406. return;
  52407. }
  52408. this._paused = true;
  52409. };
  52410. Animatable.prototype.restart = function () {
  52411. this._paused = false;
  52412. };
  52413. Animatable.prototype.stop = function (animationName) {
  52414. if (animationName) {
  52415. var idx = this._scene._activeAnimatables.indexOf(this);
  52416. if (idx > -1) {
  52417. var runtimeAnimations = this._runtimeAnimations;
  52418. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52419. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52420. continue;
  52421. }
  52422. runtimeAnimations[index].dispose();
  52423. runtimeAnimations.splice(index, 1);
  52424. }
  52425. if (runtimeAnimations.length == 0) {
  52426. this._scene._activeAnimatables.splice(idx, 1);
  52427. if (this.onAnimationEnd) {
  52428. this.onAnimationEnd();
  52429. }
  52430. }
  52431. }
  52432. }
  52433. else {
  52434. var index = this._scene._activeAnimatables.indexOf(this);
  52435. if (index > -1) {
  52436. this._scene._activeAnimatables.splice(index, 1);
  52437. var runtimeAnimations = this._runtimeAnimations;
  52438. for (var index = 0; index < runtimeAnimations.length; index++) {
  52439. runtimeAnimations[index].dispose();
  52440. }
  52441. if (this.onAnimationEnd) {
  52442. this.onAnimationEnd();
  52443. }
  52444. }
  52445. }
  52446. };
  52447. Animatable.prototype._animate = function (delay) {
  52448. if (this._paused) {
  52449. this.animationStarted = false;
  52450. if (this._pausedDelay === null) {
  52451. this._pausedDelay = delay;
  52452. }
  52453. return true;
  52454. }
  52455. if (this._localDelayOffset === null) {
  52456. this._localDelayOffset = delay;
  52457. this._pausedDelay = null;
  52458. }
  52459. else if (this._pausedDelay !== null) {
  52460. this._localDelayOffset += delay - this._pausedDelay;
  52461. this._pausedDelay = null;
  52462. }
  52463. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52464. return true;
  52465. }
  52466. // Animating
  52467. var running = false;
  52468. var runtimeAnimations = this._runtimeAnimations;
  52469. var index;
  52470. for (index = 0; index < runtimeAnimations.length; index++) {
  52471. var animation = runtimeAnimations[index];
  52472. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52473. running = running || isRunning;
  52474. }
  52475. this.animationStarted = running;
  52476. if (!running) {
  52477. // Remove from active animatables
  52478. index = this._scene._activeAnimatables.indexOf(this);
  52479. this._scene._activeAnimatables.splice(index, 1);
  52480. // Dispose all runtime animations
  52481. for (index = 0; index < runtimeAnimations.length; index++) {
  52482. runtimeAnimations[index].dispose();
  52483. }
  52484. }
  52485. if (!running && this.onAnimationEnd) {
  52486. this.onAnimationEnd();
  52487. this.onAnimationEnd = null;
  52488. }
  52489. return running;
  52490. };
  52491. return Animatable;
  52492. }());
  52493. BABYLON.Animatable = Animatable;
  52494. })(BABYLON || (BABYLON = {}));
  52495. //# sourceMappingURL=babylon.animatable.js.map
  52496. var BABYLON;
  52497. (function (BABYLON) {
  52498. var EasingFunction = /** @class */ (function () {
  52499. function EasingFunction() {
  52500. // Properties
  52501. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52502. }
  52503. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52504. get: function () {
  52505. return EasingFunction._EASINGMODE_EASEIN;
  52506. },
  52507. enumerable: true,
  52508. configurable: true
  52509. });
  52510. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52511. get: function () {
  52512. return EasingFunction._EASINGMODE_EASEOUT;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52518. get: function () {
  52519. return EasingFunction._EASINGMODE_EASEINOUT;
  52520. },
  52521. enumerable: true,
  52522. configurable: true
  52523. });
  52524. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52525. var n = Math.min(Math.max(easingMode, 0), 2);
  52526. this._easingMode = n;
  52527. };
  52528. EasingFunction.prototype.getEasingMode = function () {
  52529. return this._easingMode;
  52530. };
  52531. EasingFunction.prototype.easeInCore = function (gradient) {
  52532. throw new Error('You must implement this method');
  52533. };
  52534. EasingFunction.prototype.ease = function (gradient) {
  52535. switch (this._easingMode) {
  52536. case EasingFunction.EASINGMODE_EASEIN:
  52537. return this.easeInCore(gradient);
  52538. case EasingFunction.EASINGMODE_EASEOUT:
  52539. return (1 - this.easeInCore(1 - gradient));
  52540. }
  52541. if (gradient >= 0.5) {
  52542. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52543. }
  52544. return (this.easeInCore(gradient * 2) * 0.5);
  52545. };
  52546. //Statics
  52547. EasingFunction._EASINGMODE_EASEIN = 0;
  52548. EasingFunction._EASINGMODE_EASEOUT = 1;
  52549. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52550. return EasingFunction;
  52551. }());
  52552. BABYLON.EasingFunction = EasingFunction;
  52553. var CircleEase = /** @class */ (function (_super) {
  52554. __extends(CircleEase, _super);
  52555. function CircleEase() {
  52556. return _super !== null && _super.apply(this, arguments) || this;
  52557. }
  52558. CircleEase.prototype.easeInCore = function (gradient) {
  52559. gradient = Math.max(0, Math.min(1, gradient));
  52560. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52561. };
  52562. return CircleEase;
  52563. }(EasingFunction));
  52564. BABYLON.CircleEase = CircleEase;
  52565. var BackEase = /** @class */ (function (_super) {
  52566. __extends(BackEase, _super);
  52567. function BackEase(amplitude) {
  52568. if (amplitude === void 0) { amplitude = 1; }
  52569. var _this = _super.call(this) || this;
  52570. _this.amplitude = amplitude;
  52571. return _this;
  52572. }
  52573. BackEase.prototype.easeInCore = function (gradient) {
  52574. var num = Math.max(0, this.amplitude);
  52575. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52576. };
  52577. return BackEase;
  52578. }(EasingFunction));
  52579. BABYLON.BackEase = BackEase;
  52580. var BounceEase = /** @class */ (function (_super) {
  52581. __extends(BounceEase, _super);
  52582. function BounceEase(bounces, bounciness) {
  52583. if (bounces === void 0) { bounces = 3; }
  52584. if (bounciness === void 0) { bounciness = 2; }
  52585. var _this = _super.call(this) || this;
  52586. _this.bounces = bounces;
  52587. _this.bounciness = bounciness;
  52588. return _this;
  52589. }
  52590. BounceEase.prototype.easeInCore = function (gradient) {
  52591. var y = Math.max(0.0, this.bounces);
  52592. var bounciness = this.bounciness;
  52593. if (bounciness <= 1.0) {
  52594. bounciness = 1.001;
  52595. }
  52596. var num9 = Math.pow(bounciness, y);
  52597. var num5 = 1.0 - bounciness;
  52598. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52599. var num15 = gradient * num4;
  52600. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52601. var num3 = Math.floor(num65);
  52602. var num13 = num3 + 1.0;
  52603. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52604. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52605. var num7 = (num8 + num12) * 0.5;
  52606. var num6 = gradient - num7;
  52607. var num2 = num7 - num8;
  52608. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52609. };
  52610. return BounceEase;
  52611. }(EasingFunction));
  52612. BABYLON.BounceEase = BounceEase;
  52613. var CubicEase = /** @class */ (function (_super) {
  52614. __extends(CubicEase, _super);
  52615. function CubicEase() {
  52616. return _super !== null && _super.apply(this, arguments) || this;
  52617. }
  52618. CubicEase.prototype.easeInCore = function (gradient) {
  52619. return (gradient * gradient * gradient);
  52620. };
  52621. return CubicEase;
  52622. }(EasingFunction));
  52623. BABYLON.CubicEase = CubicEase;
  52624. var ElasticEase = /** @class */ (function (_super) {
  52625. __extends(ElasticEase, _super);
  52626. function ElasticEase(oscillations, springiness) {
  52627. if (oscillations === void 0) { oscillations = 3; }
  52628. if (springiness === void 0) { springiness = 3; }
  52629. var _this = _super.call(this) || this;
  52630. _this.oscillations = oscillations;
  52631. _this.springiness = springiness;
  52632. return _this;
  52633. }
  52634. ElasticEase.prototype.easeInCore = function (gradient) {
  52635. var num2;
  52636. var num3 = Math.max(0.0, this.oscillations);
  52637. var num = Math.max(0.0, this.springiness);
  52638. if (num == 0) {
  52639. num2 = gradient;
  52640. }
  52641. else {
  52642. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52643. }
  52644. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52645. };
  52646. return ElasticEase;
  52647. }(EasingFunction));
  52648. BABYLON.ElasticEase = ElasticEase;
  52649. var ExponentialEase = /** @class */ (function (_super) {
  52650. __extends(ExponentialEase, _super);
  52651. function ExponentialEase(exponent) {
  52652. if (exponent === void 0) { exponent = 2; }
  52653. var _this = _super.call(this) || this;
  52654. _this.exponent = exponent;
  52655. return _this;
  52656. }
  52657. ExponentialEase.prototype.easeInCore = function (gradient) {
  52658. if (this.exponent <= 0) {
  52659. return gradient;
  52660. }
  52661. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52662. };
  52663. return ExponentialEase;
  52664. }(EasingFunction));
  52665. BABYLON.ExponentialEase = ExponentialEase;
  52666. var PowerEase = /** @class */ (function (_super) {
  52667. __extends(PowerEase, _super);
  52668. function PowerEase(power) {
  52669. if (power === void 0) { power = 2; }
  52670. var _this = _super.call(this) || this;
  52671. _this.power = power;
  52672. return _this;
  52673. }
  52674. PowerEase.prototype.easeInCore = function (gradient) {
  52675. var y = Math.max(0.0, this.power);
  52676. return Math.pow(gradient, y);
  52677. };
  52678. return PowerEase;
  52679. }(EasingFunction));
  52680. BABYLON.PowerEase = PowerEase;
  52681. var QuadraticEase = /** @class */ (function (_super) {
  52682. __extends(QuadraticEase, _super);
  52683. function QuadraticEase() {
  52684. return _super !== null && _super.apply(this, arguments) || this;
  52685. }
  52686. QuadraticEase.prototype.easeInCore = function (gradient) {
  52687. return (gradient * gradient);
  52688. };
  52689. return QuadraticEase;
  52690. }(EasingFunction));
  52691. BABYLON.QuadraticEase = QuadraticEase;
  52692. var QuarticEase = /** @class */ (function (_super) {
  52693. __extends(QuarticEase, _super);
  52694. function QuarticEase() {
  52695. return _super !== null && _super.apply(this, arguments) || this;
  52696. }
  52697. QuarticEase.prototype.easeInCore = function (gradient) {
  52698. return (gradient * gradient * gradient * gradient);
  52699. };
  52700. return QuarticEase;
  52701. }(EasingFunction));
  52702. BABYLON.QuarticEase = QuarticEase;
  52703. var QuinticEase = /** @class */ (function (_super) {
  52704. __extends(QuinticEase, _super);
  52705. function QuinticEase() {
  52706. return _super !== null && _super.apply(this, arguments) || this;
  52707. }
  52708. QuinticEase.prototype.easeInCore = function (gradient) {
  52709. return (gradient * gradient * gradient * gradient * gradient);
  52710. };
  52711. return QuinticEase;
  52712. }(EasingFunction));
  52713. BABYLON.QuinticEase = QuinticEase;
  52714. var SineEase = /** @class */ (function (_super) {
  52715. __extends(SineEase, _super);
  52716. function SineEase() {
  52717. return _super !== null && _super.apply(this, arguments) || this;
  52718. }
  52719. SineEase.prototype.easeInCore = function (gradient) {
  52720. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52721. };
  52722. return SineEase;
  52723. }(EasingFunction));
  52724. BABYLON.SineEase = SineEase;
  52725. var BezierCurveEase = /** @class */ (function (_super) {
  52726. __extends(BezierCurveEase, _super);
  52727. function BezierCurveEase(x1, y1, x2, y2) {
  52728. if (x1 === void 0) { x1 = 0; }
  52729. if (y1 === void 0) { y1 = 0; }
  52730. if (x2 === void 0) { x2 = 1; }
  52731. if (y2 === void 0) { y2 = 1; }
  52732. var _this = _super.call(this) || this;
  52733. _this.x1 = x1;
  52734. _this.y1 = y1;
  52735. _this.x2 = x2;
  52736. _this.y2 = y2;
  52737. return _this;
  52738. }
  52739. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52740. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52741. };
  52742. return BezierCurveEase;
  52743. }(EasingFunction));
  52744. BABYLON.BezierCurveEase = BezierCurveEase;
  52745. })(BABYLON || (BABYLON = {}));
  52746. //# sourceMappingURL=babylon.easing.js.map
  52747. var BABYLON;
  52748. (function (BABYLON) {
  52749. /**
  52750. * A Condition applied to an Action
  52751. */
  52752. var Condition = /** @class */ (function () {
  52753. /**
  52754. * Creates a new Condition
  52755. * @param actionManager the manager of the action the condition is applied to
  52756. */
  52757. function Condition(actionManager) {
  52758. this._actionManager = actionManager;
  52759. }
  52760. /**
  52761. * Check if the current condition is valid
  52762. * @returns a boolean
  52763. */
  52764. Condition.prototype.isValid = function () {
  52765. return true;
  52766. };
  52767. /**
  52768. * Internal only
  52769. * @hidden
  52770. */
  52771. Condition.prototype._getProperty = function (propertyPath) {
  52772. return this._actionManager._getProperty(propertyPath);
  52773. };
  52774. /**
  52775. * Internal only
  52776. * @hidden
  52777. */
  52778. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52779. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52780. };
  52781. /**
  52782. * Serialize placeholder for child classes
  52783. * @returns the serialized object
  52784. */
  52785. Condition.prototype.serialize = function () {
  52786. };
  52787. /**
  52788. * Internal only
  52789. * @hidden
  52790. */
  52791. Condition.prototype._serialize = function (serializedCondition) {
  52792. return {
  52793. type: 2,
  52794. children: [],
  52795. name: serializedCondition.name,
  52796. properties: serializedCondition.properties
  52797. };
  52798. };
  52799. return Condition;
  52800. }());
  52801. BABYLON.Condition = Condition;
  52802. /**
  52803. * Defines specific conditional operators as extensions of Condition
  52804. */
  52805. var ValueCondition = /** @class */ (function (_super) {
  52806. __extends(ValueCondition, _super);
  52807. /**
  52808. * Creates a new ValueCondition
  52809. * @param actionManager manager for the action the condition applies to
  52810. * @param target for the action
  52811. * @param propertyPath path to specify the property of the target the conditional operator uses
  52812. * @param value the value compared by the conditional operator against the current value of the property
  52813. * @param operator the conditional operator, default ValueCondition.IsEqual
  52814. */
  52815. function ValueCondition(actionManager, target,
  52816. /** path to specify the property of the target the conditional operator uses */
  52817. propertyPath,
  52818. /** the value compared by the conditional operator against the current value of the property */
  52819. value,
  52820. /** the conditional operator, default ValueCondition.IsEqual */
  52821. operator) {
  52822. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52823. var _this = _super.call(this, actionManager) || this;
  52824. _this.propertyPath = propertyPath;
  52825. _this.value = value;
  52826. _this.operator = operator;
  52827. _this._target = target;
  52828. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52829. _this._property = _this._getProperty(_this.propertyPath);
  52830. return _this;
  52831. }
  52832. Object.defineProperty(ValueCondition, "IsEqual", {
  52833. /**
  52834. * returns the number for IsEqual
  52835. */
  52836. get: function () {
  52837. return ValueCondition._IsEqual;
  52838. },
  52839. enumerable: true,
  52840. configurable: true
  52841. });
  52842. Object.defineProperty(ValueCondition, "IsDifferent", {
  52843. /**
  52844. * Returns the number for IsDifferent
  52845. */
  52846. get: function () {
  52847. return ValueCondition._IsDifferent;
  52848. },
  52849. enumerable: true,
  52850. configurable: true
  52851. });
  52852. Object.defineProperty(ValueCondition, "IsGreater", {
  52853. /**
  52854. * Returns the number for IsGreater
  52855. */
  52856. get: function () {
  52857. return ValueCondition._IsGreater;
  52858. },
  52859. enumerable: true,
  52860. configurable: true
  52861. });
  52862. Object.defineProperty(ValueCondition, "IsLesser", {
  52863. /**
  52864. * Returns the number for IsLesser
  52865. */
  52866. get: function () {
  52867. return ValueCondition._IsLesser;
  52868. },
  52869. enumerable: true,
  52870. configurable: true
  52871. });
  52872. /**
  52873. * Compares the given value with the property value for the specified conditional operator
  52874. * @returns the result of the comparison
  52875. */
  52876. ValueCondition.prototype.isValid = function () {
  52877. switch (this.operator) {
  52878. case ValueCondition.IsGreater:
  52879. return this._effectiveTarget[this._property] > this.value;
  52880. case ValueCondition.IsLesser:
  52881. return this._effectiveTarget[this._property] < this.value;
  52882. case ValueCondition.IsEqual:
  52883. case ValueCondition.IsDifferent:
  52884. var check;
  52885. if (this.value.equals) {
  52886. check = this.value.equals(this._effectiveTarget[this._property]);
  52887. }
  52888. else {
  52889. check = this.value === this._effectiveTarget[this._property];
  52890. }
  52891. return this.operator === ValueCondition.IsEqual ? check : !check;
  52892. }
  52893. return false;
  52894. };
  52895. /**
  52896. * Serialize the ValueCondition into a JSON compatible object
  52897. * @returns serialization object
  52898. */
  52899. ValueCondition.prototype.serialize = function () {
  52900. return this._serialize({
  52901. name: "ValueCondition",
  52902. properties: [
  52903. BABYLON.Action._GetTargetProperty(this._target),
  52904. { name: "propertyPath", value: this.propertyPath },
  52905. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52906. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52907. ]
  52908. });
  52909. };
  52910. /**
  52911. * Gets the name of the conditional operator for the ValueCondition
  52912. * @param operator the conditional operator
  52913. * @returns the name
  52914. */
  52915. ValueCondition.GetOperatorName = function (operator) {
  52916. switch (operator) {
  52917. case ValueCondition._IsEqual: return "IsEqual";
  52918. case ValueCondition._IsDifferent: return "IsDifferent";
  52919. case ValueCondition._IsGreater: return "IsGreater";
  52920. case ValueCondition._IsLesser: return "IsLesser";
  52921. default: return "";
  52922. }
  52923. };
  52924. /**
  52925. * Internal only
  52926. * @hidden
  52927. */
  52928. ValueCondition._IsEqual = 0;
  52929. /**
  52930. * Internal only
  52931. * @hidden
  52932. */
  52933. ValueCondition._IsDifferent = 1;
  52934. /**
  52935. * Internal only
  52936. * @hidden
  52937. */
  52938. ValueCondition._IsGreater = 2;
  52939. /**
  52940. * Internal only
  52941. * @hidden
  52942. */
  52943. ValueCondition._IsLesser = 3;
  52944. return ValueCondition;
  52945. }(Condition));
  52946. BABYLON.ValueCondition = ValueCondition;
  52947. /**
  52948. * Defines a predicate condition as an extension of Condition
  52949. */
  52950. var PredicateCondition = /** @class */ (function (_super) {
  52951. __extends(PredicateCondition, _super);
  52952. /**
  52953. * Creates a new PredicateCondition
  52954. * @param actionManager manager for the action the condition applies to
  52955. * @param predicate defines the predicate function used to validate the condition
  52956. */
  52957. function PredicateCondition(actionManager,
  52958. /** defines the predicate function used to validate the condition */
  52959. predicate) {
  52960. var _this = _super.call(this, actionManager) || this;
  52961. _this.predicate = predicate;
  52962. return _this;
  52963. }
  52964. /**
  52965. * @returns the validity of the predicate condition
  52966. */
  52967. PredicateCondition.prototype.isValid = function () {
  52968. return this.predicate();
  52969. };
  52970. return PredicateCondition;
  52971. }(Condition));
  52972. BABYLON.PredicateCondition = PredicateCondition;
  52973. /**
  52974. * Defines a state condition as an extension of Condition
  52975. */
  52976. var StateCondition = /** @class */ (function (_super) {
  52977. __extends(StateCondition, _super);
  52978. /**
  52979. * Creates a new StateCondition
  52980. * @param actionManager manager for the action the condition applies to
  52981. * @param target of the condition
  52982. * @param value to compare with target state
  52983. */
  52984. function StateCondition(actionManager, target, value) {
  52985. var _this = _super.call(this, actionManager) || this;
  52986. _this.value = value;
  52987. _this._target = target;
  52988. return _this;
  52989. }
  52990. /**
  52991. * @returns the validity of the state
  52992. */
  52993. StateCondition.prototype.isValid = function () {
  52994. return this._target.state === this.value;
  52995. };
  52996. /**
  52997. * Serialize the StateCondition into a JSON compatible object
  52998. * @returns serialization object
  52999. */
  53000. StateCondition.prototype.serialize = function () {
  53001. return this._serialize({
  53002. name: "StateCondition",
  53003. properties: [
  53004. BABYLON.Action._GetTargetProperty(this._target),
  53005. { name: "value", value: this.value }
  53006. ]
  53007. });
  53008. };
  53009. return StateCondition;
  53010. }(Condition));
  53011. BABYLON.StateCondition = StateCondition;
  53012. })(BABYLON || (BABYLON = {}));
  53013. //# sourceMappingURL=babylon.condition.js.map
  53014. var BABYLON;
  53015. (function (BABYLON) {
  53016. /**
  53017. * The action to be carried out following a trigger
  53018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53019. */
  53020. var Action = /** @class */ (function () {
  53021. /**
  53022. * Creates a new Action
  53023. * @param triggerOptions the trigger, with or without parameters, for the action
  53024. * @param condition an optional determinant of action
  53025. */
  53026. function Action(
  53027. /** the trigger, with or without parameters, for the action */
  53028. triggerOptions, condition) {
  53029. this.triggerOptions = triggerOptions;
  53030. /**
  53031. * An event triggered prior to action being executed.
  53032. */
  53033. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53034. if (triggerOptions.parameter) {
  53035. this.trigger = triggerOptions.trigger;
  53036. this._triggerParameter = triggerOptions.parameter;
  53037. }
  53038. else {
  53039. this.trigger = triggerOptions;
  53040. }
  53041. this._nextActiveAction = this;
  53042. this._condition = condition;
  53043. }
  53044. /**
  53045. * Internal only
  53046. * @hidden
  53047. */
  53048. Action.prototype._prepare = function () {
  53049. };
  53050. /**
  53051. * Gets the trigger parameters
  53052. * @returns the trigger parameters
  53053. */
  53054. Action.prototype.getTriggerParameter = function () {
  53055. return this._triggerParameter;
  53056. };
  53057. /**
  53058. * Internal only - executes current action event
  53059. * @hidden
  53060. */
  53061. Action.prototype._executeCurrent = function (evt) {
  53062. if (this._nextActiveAction._condition) {
  53063. var condition = this._nextActiveAction._condition;
  53064. var currentRenderId = this._actionManager.getScene().getRenderId();
  53065. // We cache the current evaluation for the current frame
  53066. if (condition._evaluationId === currentRenderId) {
  53067. if (!condition._currentResult) {
  53068. return;
  53069. }
  53070. }
  53071. else {
  53072. condition._evaluationId = currentRenderId;
  53073. if (!condition.isValid()) {
  53074. condition._currentResult = false;
  53075. return;
  53076. }
  53077. condition._currentResult = true;
  53078. }
  53079. }
  53080. this.onBeforeExecuteObservable.notifyObservers(this);
  53081. this._nextActiveAction.execute(evt);
  53082. this.skipToNextActiveAction();
  53083. };
  53084. /**
  53085. * Execute placeholder for child classes
  53086. * @param evt optional action event
  53087. */
  53088. Action.prototype.execute = function (evt) {
  53089. };
  53090. /**
  53091. * Skips to next active action
  53092. */
  53093. Action.prototype.skipToNextActiveAction = function () {
  53094. if (this._nextActiveAction._child) {
  53095. if (!this._nextActiveAction._child._actionManager) {
  53096. this._nextActiveAction._child._actionManager = this._actionManager;
  53097. }
  53098. this._nextActiveAction = this._nextActiveAction._child;
  53099. }
  53100. else {
  53101. this._nextActiveAction = this;
  53102. }
  53103. };
  53104. /**
  53105. * Adds action to chain of actions, may be a DoNothingAction
  53106. * @param action defines the next action to execute
  53107. * @returns The action passed in
  53108. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53109. */
  53110. Action.prototype.then = function (action) {
  53111. this._child = action;
  53112. action._actionManager = this._actionManager;
  53113. action._prepare();
  53114. return action;
  53115. };
  53116. /**
  53117. * Internal only
  53118. * @hidden
  53119. */
  53120. Action.prototype._getProperty = function (propertyPath) {
  53121. return this._actionManager._getProperty(propertyPath);
  53122. };
  53123. /**
  53124. * Internal only
  53125. * @hidden
  53126. */
  53127. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53128. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53129. };
  53130. /**
  53131. * Serialize placeholder for child classes
  53132. * @param parent of child
  53133. * @returns the serialized object
  53134. */
  53135. Action.prototype.serialize = function (parent) {
  53136. };
  53137. /**
  53138. * Internal only called by serialize
  53139. * @hidden
  53140. */
  53141. Action.prototype._serialize = function (serializedAction, parent) {
  53142. var serializationObject = {
  53143. type: 1,
  53144. children: [],
  53145. name: serializedAction.name,
  53146. properties: serializedAction.properties || []
  53147. };
  53148. // Serialize child
  53149. if (this._child) {
  53150. this._child.serialize(serializationObject);
  53151. }
  53152. // Check if "this" has a condition
  53153. if (this._condition) {
  53154. var serializedCondition = this._condition.serialize();
  53155. serializedCondition.children.push(serializationObject);
  53156. if (parent) {
  53157. parent.children.push(serializedCondition);
  53158. }
  53159. return serializedCondition;
  53160. }
  53161. if (parent) {
  53162. parent.children.push(serializationObject);
  53163. }
  53164. return serializationObject;
  53165. };
  53166. /**
  53167. * Internal only
  53168. * @hidden
  53169. */
  53170. Action._SerializeValueAsString = function (value) {
  53171. if (typeof value === "number") {
  53172. return value.toString();
  53173. }
  53174. if (typeof value === "boolean") {
  53175. return value ? "true" : "false";
  53176. }
  53177. if (value instanceof BABYLON.Vector2) {
  53178. return value.x + ", " + value.y;
  53179. }
  53180. if (value instanceof BABYLON.Vector3) {
  53181. return value.x + ", " + value.y + ", " + value.z;
  53182. }
  53183. if (value instanceof BABYLON.Color3) {
  53184. return value.r + ", " + value.g + ", " + value.b;
  53185. }
  53186. if (value instanceof BABYLON.Color4) {
  53187. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53188. }
  53189. return value; // string
  53190. };
  53191. /**
  53192. * Internal only
  53193. * @hidden
  53194. */
  53195. Action._GetTargetProperty = function (target) {
  53196. return {
  53197. name: "target",
  53198. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53199. : target instanceof BABYLON.Light ? "LightProperties"
  53200. : target instanceof BABYLON.Camera ? "CameraProperties"
  53201. : "SceneProperties",
  53202. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53203. };
  53204. };
  53205. return Action;
  53206. }());
  53207. BABYLON.Action = Action;
  53208. })(BABYLON || (BABYLON = {}));
  53209. //# sourceMappingURL=babylon.action.js.map
  53210. var BABYLON;
  53211. (function (BABYLON) {
  53212. /**
  53213. * ActionEvent is the event being sent when an action is triggered.
  53214. */
  53215. var ActionEvent = /** @class */ (function () {
  53216. /**
  53217. * Creates a new ActionEvent
  53218. * @param source The mesh or sprite that triggered the action
  53219. * @param pointerX The X mouse cursor position at the time of the event
  53220. * @param pointerY The Y mouse cursor position at the time of the event
  53221. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53222. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53223. * @param additionalData additional data for the event
  53224. */
  53225. function ActionEvent(
  53226. /** The mesh or sprite that triggered the action */
  53227. source,
  53228. /** The X mouse cursor position at the time of the event */
  53229. pointerX,
  53230. /** The Y mouse cursor position at the time of the event */
  53231. pointerY,
  53232. /** The mesh that is currently pointed at (can be null) */
  53233. meshUnderPointer,
  53234. /** the original (browser) event that triggered the ActionEvent */
  53235. sourceEvent,
  53236. /** additional data for the event */
  53237. additionalData) {
  53238. this.source = source;
  53239. this.pointerX = pointerX;
  53240. this.pointerY = pointerY;
  53241. this.meshUnderPointer = meshUnderPointer;
  53242. this.sourceEvent = sourceEvent;
  53243. this.additionalData = additionalData;
  53244. }
  53245. /**
  53246. * Helper function to auto-create an ActionEvent from a source mesh.
  53247. * @param source The source mesh that triggered the event
  53248. * @param evt The original (browser) event
  53249. * @param additionalData additional data for the event
  53250. * @returns the new ActionEvent
  53251. */
  53252. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53253. var scene = source.getScene();
  53254. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53255. };
  53256. /**
  53257. * Helper function to auto-create an ActionEvent from a source sprite
  53258. * @param source The source sprite that triggered the event
  53259. * @param scene Scene associated with the sprite
  53260. * @param evt The original (browser) event
  53261. * @param additionalData additional data for the event
  53262. * @returns the new ActionEvent
  53263. */
  53264. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53265. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53266. };
  53267. /**
  53268. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53269. * @param scene the scene where the event occurred
  53270. * @param evt The original (browser) event
  53271. * @returns the new ActionEvent
  53272. */
  53273. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53274. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53275. };
  53276. /**
  53277. * Helper function to auto-create an ActionEvent from a primitive
  53278. * @param prim defines the target primitive
  53279. * @param pointerPos defines the pointer position
  53280. * @param evt The original (browser) event
  53281. * @param additionalData additional data for the event
  53282. * @returns the new ActionEvent
  53283. */
  53284. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53285. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53286. };
  53287. return ActionEvent;
  53288. }());
  53289. BABYLON.ActionEvent = ActionEvent;
  53290. /**
  53291. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53292. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53293. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53294. */
  53295. var ActionManager = /** @class */ (function () {
  53296. /**
  53297. * Creates a new action manager
  53298. * @param scene defines the hosting scene
  53299. */
  53300. function ActionManager(scene) {
  53301. // Members
  53302. /** Gets the list of actions */
  53303. this.actions = new Array();
  53304. /** Gets the cursor to use when hovering items */
  53305. this.hoverCursor = '';
  53306. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53307. scene._actionManagers.push(this);
  53308. }
  53309. Object.defineProperty(ActionManager, "NothingTrigger", {
  53310. /**
  53311. * Nothing
  53312. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53313. */
  53314. get: function () {
  53315. return ActionManager._NothingTrigger;
  53316. },
  53317. enumerable: true,
  53318. configurable: true
  53319. });
  53320. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53321. /**
  53322. * On pick
  53323. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53324. */
  53325. get: function () {
  53326. return ActionManager._OnPickTrigger;
  53327. },
  53328. enumerable: true,
  53329. configurable: true
  53330. });
  53331. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53332. /**
  53333. * On left pick
  53334. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53335. */
  53336. get: function () {
  53337. return ActionManager._OnLeftPickTrigger;
  53338. },
  53339. enumerable: true,
  53340. configurable: true
  53341. });
  53342. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53343. /**
  53344. * On right pick
  53345. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53346. */
  53347. get: function () {
  53348. return ActionManager._OnRightPickTrigger;
  53349. },
  53350. enumerable: true,
  53351. configurable: true
  53352. });
  53353. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53354. /**
  53355. * On center pick
  53356. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53357. */
  53358. get: function () {
  53359. return ActionManager._OnCenterPickTrigger;
  53360. },
  53361. enumerable: true,
  53362. configurable: true
  53363. });
  53364. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53365. /**
  53366. * On pick down
  53367. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53368. */
  53369. get: function () {
  53370. return ActionManager._OnPickDownTrigger;
  53371. },
  53372. enumerable: true,
  53373. configurable: true
  53374. });
  53375. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53376. /**
  53377. * On double pick
  53378. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53379. */
  53380. get: function () {
  53381. return ActionManager._OnDoublePickTrigger;
  53382. },
  53383. enumerable: true,
  53384. configurable: true
  53385. });
  53386. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53387. /**
  53388. * On pick up
  53389. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53390. */
  53391. get: function () {
  53392. return ActionManager._OnPickUpTrigger;
  53393. },
  53394. enumerable: true,
  53395. configurable: true
  53396. });
  53397. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53398. /**
  53399. * On pick out.
  53400. * This trigger will only be raised if you also declared a OnPickDown
  53401. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53402. */
  53403. get: function () {
  53404. return ActionManager._OnPickOutTrigger;
  53405. },
  53406. enumerable: true,
  53407. configurable: true
  53408. });
  53409. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53410. /**
  53411. * On long press
  53412. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53413. */
  53414. get: function () {
  53415. return ActionManager._OnLongPressTrigger;
  53416. },
  53417. enumerable: true,
  53418. configurable: true
  53419. });
  53420. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53421. /**
  53422. * On pointer over
  53423. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53424. */
  53425. get: function () {
  53426. return ActionManager._OnPointerOverTrigger;
  53427. },
  53428. enumerable: true,
  53429. configurable: true
  53430. });
  53431. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53432. /**
  53433. * On pointer out
  53434. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53435. */
  53436. get: function () {
  53437. return ActionManager._OnPointerOutTrigger;
  53438. },
  53439. enumerable: true,
  53440. configurable: true
  53441. });
  53442. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53443. /**
  53444. * On every frame
  53445. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53446. */
  53447. get: function () {
  53448. return ActionManager._OnEveryFrameTrigger;
  53449. },
  53450. enumerable: true,
  53451. configurable: true
  53452. });
  53453. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53454. /**
  53455. * On intersection enter
  53456. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53457. */
  53458. get: function () {
  53459. return ActionManager._OnIntersectionEnterTrigger;
  53460. },
  53461. enumerable: true,
  53462. configurable: true
  53463. });
  53464. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53465. /**
  53466. * On intersection exit
  53467. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53468. */
  53469. get: function () {
  53470. return ActionManager._OnIntersectionExitTrigger;
  53471. },
  53472. enumerable: true,
  53473. configurable: true
  53474. });
  53475. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53476. /**
  53477. * On key down
  53478. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53479. */
  53480. get: function () {
  53481. return ActionManager._OnKeyDownTrigger;
  53482. },
  53483. enumerable: true,
  53484. configurable: true
  53485. });
  53486. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53487. /**
  53488. * On key up
  53489. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53490. */
  53491. get: function () {
  53492. return ActionManager._OnKeyUpTrigger;
  53493. },
  53494. enumerable: true,
  53495. configurable: true
  53496. });
  53497. // Methods
  53498. /**
  53499. * Releases all associated resources
  53500. */
  53501. ActionManager.prototype.dispose = function () {
  53502. var index = this._scene._actionManagers.indexOf(this);
  53503. for (var i = 0; i < this.actions.length; i++) {
  53504. var action = this.actions[i];
  53505. ActionManager.Triggers[action.trigger]--;
  53506. if (ActionManager.Triggers[action.trigger] === 0) {
  53507. delete ActionManager.Triggers[action.trigger];
  53508. }
  53509. }
  53510. if (index > -1) {
  53511. this._scene._actionManagers.splice(index, 1);
  53512. }
  53513. };
  53514. /**
  53515. * Gets hosting scene
  53516. * @returns the hosting scene
  53517. */
  53518. ActionManager.prototype.getScene = function () {
  53519. return this._scene;
  53520. };
  53521. /**
  53522. * Does this action manager handles actions of any of the given triggers
  53523. * @param triggers defines the triggers to be tested
  53524. * @return a boolean indicating whether one (or more) of the triggers is handled
  53525. */
  53526. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53527. for (var index = 0; index < this.actions.length; index++) {
  53528. var action = this.actions[index];
  53529. if (triggers.indexOf(action.trigger) > -1) {
  53530. return true;
  53531. }
  53532. }
  53533. return false;
  53534. };
  53535. /**
  53536. * Does this action manager handles actions of a given trigger
  53537. * @param trigger defines the trigger to be tested
  53538. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53539. * @return whether the trigger is handled
  53540. */
  53541. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53542. for (var index = 0; index < this.actions.length; index++) {
  53543. var action = this.actions[index];
  53544. if (action.trigger === trigger) {
  53545. if (parameterPredicate) {
  53546. if (parameterPredicate(action.getTriggerParameter())) {
  53547. return true;
  53548. }
  53549. }
  53550. else {
  53551. return true;
  53552. }
  53553. }
  53554. }
  53555. return false;
  53556. };
  53557. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53558. /**
  53559. * Does this action manager has pointer triggers
  53560. */
  53561. get: function () {
  53562. for (var index = 0; index < this.actions.length; index++) {
  53563. var action = this.actions[index];
  53564. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53565. return true;
  53566. }
  53567. }
  53568. return false;
  53569. },
  53570. enumerable: true,
  53571. configurable: true
  53572. });
  53573. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53574. /**
  53575. * Does this action manager has pick triggers
  53576. */
  53577. get: function () {
  53578. for (var index = 0; index < this.actions.length; index++) {
  53579. var action = this.actions[index];
  53580. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53581. return true;
  53582. }
  53583. }
  53584. return false;
  53585. },
  53586. enumerable: true,
  53587. configurable: true
  53588. });
  53589. Object.defineProperty(ActionManager, "HasTriggers", {
  53590. /**
  53591. * Does exist one action manager with at least one trigger
  53592. **/
  53593. get: function () {
  53594. for (var t in ActionManager.Triggers) {
  53595. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53596. return true;
  53597. }
  53598. }
  53599. return false;
  53600. },
  53601. enumerable: true,
  53602. configurable: true
  53603. });
  53604. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53605. /**
  53606. * Does exist one action manager with at least one pick trigger
  53607. **/
  53608. get: function () {
  53609. for (var t in ActionManager.Triggers) {
  53610. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53611. var t_int = parseInt(t);
  53612. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53613. return true;
  53614. }
  53615. }
  53616. }
  53617. return false;
  53618. },
  53619. enumerable: true,
  53620. configurable: true
  53621. });
  53622. /**
  53623. * Does exist one action manager that handles actions of a given trigger
  53624. * @param trigger defines the trigger to be tested
  53625. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53626. **/
  53627. ActionManager.HasSpecificTrigger = function (trigger) {
  53628. for (var t in ActionManager.Triggers) {
  53629. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53630. var t_int = parseInt(t);
  53631. if (t_int === trigger) {
  53632. return true;
  53633. }
  53634. }
  53635. }
  53636. return false;
  53637. };
  53638. /**
  53639. * Registers an action to this action manager
  53640. * @param action defines the action to be registered
  53641. * @return the action amended (prepared) after registration
  53642. */
  53643. ActionManager.prototype.registerAction = function (action) {
  53644. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53645. if (this.getScene().actionManager !== this) {
  53646. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53647. return null;
  53648. }
  53649. }
  53650. this.actions.push(action);
  53651. if (ActionManager.Triggers[action.trigger]) {
  53652. ActionManager.Triggers[action.trigger]++;
  53653. }
  53654. else {
  53655. ActionManager.Triggers[action.trigger] = 1;
  53656. }
  53657. action._actionManager = this;
  53658. action._prepare();
  53659. return action;
  53660. };
  53661. /**
  53662. * Unregisters an action to this action manager
  53663. * @param action defines the action to be unregistered
  53664. * @return a boolean indicating whether the action has been unregistered
  53665. */
  53666. ActionManager.prototype.unregisterAction = function (action) {
  53667. var index = this.actions.indexOf(action);
  53668. if (index !== -1) {
  53669. this.actions.splice(index, 1);
  53670. ActionManager.Triggers[action.trigger] -= 1;
  53671. if (ActionManager.Triggers[action.trigger] === 0) {
  53672. delete ActionManager.Triggers[action.trigger];
  53673. }
  53674. delete action._actionManager;
  53675. return true;
  53676. }
  53677. return false;
  53678. };
  53679. /**
  53680. * Process a specific trigger
  53681. * @param trigger defines the trigger to process
  53682. * @param evt defines the event details to be processed
  53683. */
  53684. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53685. for (var index = 0; index < this.actions.length; index++) {
  53686. var action = this.actions[index];
  53687. if (action.trigger === trigger) {
  53688. if (evt) {
  53689. if (trigger === ActionManager.OnKeyUpTrigger
  53690. || trigger === ActionManager.OnKeyDownTrigger) {
  53691. var parameter = action.getTriggerParameter();
  53692. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53693. if (!parameter.toLowerCase) {
  53694. continue;
  53695. }
  53696. var lowerCase = parameter.toLowerCase();
  53697. if (lowerCase !== evt.sourceEvent.key) {
  53698. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53699. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53700. if (actualkey !== lowerCase) {
  53701. continue;
  53702. }
  53703. }
  53704. }
  53705. }
  53706. }
  53707. action._executeCurrent(evt);
  53708. }
  53709. }
  53710. };
  53711. /** @hidden */
  53712. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53713. var properties = propertyPath.split(".");
  53714. for (var index = 0; index < properties.length - 1; index++) {
  53715. target = target[properties[index]];
  53716. }
  53717. return target;
  53718. };
  53719. /** @hidden */
  53720. ActionManager.prototype._getProperty = function (propertyPath) {
  53721. var properties = propertyPath.split(".");
  53722. return properties[properties.length - 1];
  53723. };
  53724. /**
  53725. * Serialize this manager to a JSON object
  53726. * @param name defines the property name to store this manager
  53727. * @returns a JSON representation of this manager
  53728. */
  53729. ActionManager.prototype.serialize = function (name) {
  53730. var root = {
  53731. children: new Array(),
  53732. name: name,
  53733. type: 3,
  53734. properties: new Array() // Empty for root but required
  53735. };
  53736. for (var i = 0; i < this.actions.length; i++) {
  53737. var triggerObject = {
  53738. type: 0,
  53739. children: new Array(),
  53740. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53741. properties: new Array()
  53742. };
  53743. var triggerOptions = this.actions[i].triggerOptions;
  53744. if (triggerOptions && typeof triggerOptions !== "number") {
  53745. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53746. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53747. }
  53748. else {
  53749. var parameter = {};
  53750. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53751. if (triggerOptions.parameter.mesh) {
  53752. parameter._meshId = triggerOptions.parameter.mesh.id;
  53753. }
  53754. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53755. }
  53756. }
  53757. // Serialize child action, recursively
  53758. this.actions[i].serialize(triggerObject);
  53759. // Add serialized trigger
  53760. root.children.push(triggerObject);
  53761. }
  53762. return root;
  53763. };
  53764. /**
  53765. * Creates a new ActionManager from a JSON data
  53766. * @param parsedActions defines the JSON data to read from
  53767. * @param object defines the hosting mesh
  53768. * @param scene defines the hosting scene
  53769. */
  53770. ActionManager.Parse = function (parsedActions, object, scene) {
  53771. var actionManager = new ActionManager(scene);
  53772. if (object === null)
  53773. scene.actionManager = actionManager;
  53774. else
  53775. object.actionManager = actionManager;
  53776. // instanciate a new object
  53777. var instanciate = function (name, params) {
  53778. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53779. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53780. newInstance.constructor.apply(newInstance, params);
  53781. return newInstance;
  53782. };
  53783. var parseParameter = function (name, value, target, propertyPath) {
  53784. if (propertyPath === null) {
  53785. // String, boolean or float
  53786. var floatValue = parseFloat(value);
  53787. if (value === "true" || value === "false")
  53788. return value === "true";
  53789. else
  53790. return isNaN(floatValue) ? value : floatValue;
  53791. }
  53792. var effectiveTarget = propertyPath.split(".");
  53793. var values = value.split(",");
  53794. // Get effective Target
  53795. for (var i = 0; i < effectiveTarget.length; i++) {
  53796. target = target[effectiveTarget[i]];
  53797. }
  53798. // Return appropriate value with its type
  53799. if (typeof (target) === "boolean")
  53800. return values[0] === "true";
  53801. if (typeof (target) === "string")
  53802. return values[0];
  53803. // Parameters with multiple values such as Vector3 etc.
  53804. var split = new Array();
  53805. for (var i = 0; i < values.length; i++)
  53806. split.push(parseFloat(values[i]));
  53807. if (target instanceof BABYLON.Vector3)
  53808. return BABYLON.Vector3.FromArray(split);
  53809. if (target instanceof BABYLON.Vector4)
  53810. return BABYLON.Vector4.FromArray(split);
  53811. if (target instanceof BABYLON.Color3)
  53812. return BABYLON.Color3.FromArray(split);
  53813. if (target instanceof BABYLON.Color4)
  53814. return BABYLON.Color4.FromArray(split);
  53815. return parseFloat(values[0]);
  53816. };
  53817. // traverse graph per trigger
  53818. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53819. if (combineArray === void 0) { combineArray = null; }
  53820. if (parsedAction.detached)
  53821. return;
  53822. var parameters = new Array();
  53823. var target = null;
  53824. var propertyPath = null;
  53825. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53826. // Parameters
  53827. if (parsedAction.type === 2)
  53828. parameters.push(actionManager);
  53829. else
  53830. parameters.push(trigger);
  53831. if (combine) {
  53832. var actions = new Array();
  53833. for (var j = 0; j < parsedAction.combine.length; j++) {
  53834. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53835. }
  53836. parameters.push(actions);
  53837. }
  53838. else {
  53839. for (var i = 0; i < parsedAction.properties.length; i++) {
  53840. var value = parsedAction.properties[i].value;
  53841. var name = parsedAction.properties[i].name;
  53842. var targetType = parsedAction.properties[i].targetType;
  53843. if (name === "target")
  53844. if (targetType !== null && targetType === "SceneProperties")
  53845. value = target = scene;
  53846. else
  53847. value = target = scene.getNodeByName(value);
  53848. else if (name === "parent")
  53849. value = scene.getNodeByName(value);
  53850. else if (name === "sound")
  53851. value = scene.getSoundByName(value);
  53852. else if (name !== "propertyPath") {
  53853. if (parsedAction.type === 2 && name === "operator")
  53854. value = BABYLON.ValueCondition[value];
  53855. else
  53856. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53857. }
  53858. else {
  53859. propertyPath = value;
  53860. }
  53861. parameters.push(value);
  53862. }
  53863. }
  53864. if (combineArray === null) {
  53865. parameters.push(condition);
  53866. }
  53867. else {
  53868. parameters.push(null);
  53869. }
  53870. // If interpolate value action
  53871. if (parsedAction.name === "InterpolateValueAction") {
  53872. var param = parameters[parameters.length - 2];
  53873. parameters[parameters.length - 1] = param;
  53874. parameters[parameters.length - 2] = condition;
  53875. }
  53876. // Action or condition(s) and not CombineAction
  53877. var newAction = instanciate(parsedAction.name, parameters);
  53878. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53879. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53880. if (action)
  53881. action.then(nothing);
  53882. else
  53883. actionManager.registerAction(nothing);
  53884. action = nothing;
  53885. }
  53886. if (combineArray === null) {
  53887. if (newAction instanceof BABYLON.Condition) {
  53888. condition = newAction;
  53889. newAction = action;
  53890. }
  53891. else {
  53892. condition = null;
  53893. if (action)
  53894. action.then(newAction);
  53895. else
  53896. actionManager.registerAction(newAction);
  53897. }
  53898. }
  53899. else {
  53900. combineArray.push(newAction);
  53901. }
  53902. for (var i = 0; i < parsedAction.children.length; i++)
  53903. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53904. };
  53905. // triggers
  53906. for (var i = 0; i < parsedActions.children.length; i++) {
  53907. var triggerParams;
  53908. var trigger = parsedActions.children[i];
  53909. if (trigger.properties.length > 0) {
  53910. var param = trigger.properties[0].value;
  53911. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53912. if (value._meshId) {
  53913. value.mesh = scene.getMeshByID(value._meshId);
  53914. }
  53915. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53916. }
  53917. else
  53918. triggerParams = ActionManager[trigger.name];
  53919. for (var j = 0; j < trigger.children.length; j++) {
  53920. if (!trigger.detached)
  53921. traverse(trigger.children[j], triggerParams, null, null);
  53922. }
  53923. }
  53924. };
  53925. /**
  53926. * Get a trigger name by index
  53927. * @param trigger defines the trigger index
  53928. * @returns a trigger name
  53929. */
  53930. ActionManager.GetTriggerName = function (trigger) {
  53931. switch (trigger) {
  53932. case 0: return "NothingTrigger";
  53933. case 1: return "OnPickTrigger";
  53934. case 2: return "OnLeftPickTrigger";
  53935. case 3: return "OnRightPickTrigger";
  53936. case 4: return "OnCenterPickTrigger";
  53937. case 5: return "OnPickDownTrigger";
  53938. case 6: return "OnPickUpTrigger";
  53939. case 7: return "OnLongPressTrigger";
  53940. case 8: return "OnPointerOverTrigger";
  53941. case 9: return "OnPointerOutTrigger";
  53942. case 10: return "OnEveryFrameTrigger";
  53943. case 11: return "OnIntersectionEnterTrigger";
  53944. case 12: return "OnIntersectionExitTrigger";
  53945. case 13: return "OnKeyDownTrigger";
  53946. case 14: return "OnKeyUpTrigger";
  53947. case 15: return "OnPickOutTrigger";
  53948. default: return "";
  53949. }
  53950. };
  53951. // Statics
  53952. ActionManager._NothingTrigger = 0;
  53953. ActionManager._OnPickTrigger = 1;
  53954. ActionManager._OnLeftPickTrigger = 2;
  53955. ActionManager._OnRightPickTrigger = 3;
  53956. ActionManager._OnCenterPickTrigger = 4;
  53957. ActionManager._OnPickDownTrigger = 5;
  53958. ActionManager._OnDoublePickTrigger = 6;
  53959. ActionManager._OnPickUpTrigger = 7;
  53960. ActionManager._OnLongPressTrigger = 8;
  53961. ActionManager._OnPointerOverTrigger = 9;
  53962. ActionManager._OnPointerOutTrigger = 10;
  53963. ActionManager._OnEveryFrameTrigger = 11;
  53964. ActionManager._OnIntersectionEnterTrigger = 12;
  53965. ActionManager._OnIntersectionExitTrigger = 13;
  53966. ActionManager._OnKeyDownTrigger = 14;
  53967. ActionManager._OnKeyUpTrigger = 15;
  53968. ActionManager._OnPickOutTrigger = 16;
  53969. /** Gets the list of active triggers */
  53970. ActionManager.Triggers = {};
  53971. return ActionManager;
  53972. }());
  53973. BABYLON.ActionManager = ActionManager;
  53974. })(BABYLON || (BABYLON = {}));
  53975. //# sourceMappingURL=babylon.actionManager.js.map
  53976. var BABYLON;
  53977. (function (BABYLON) {
  53978. var InterpolateValueAction = /** @class */ (function (_super) {
  53979. __extends(InterpolateValueAction, _super);
  53980. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53981. if (duration === void 0) { duration = 1000; }
  53982. var _this = _super.call(this, triggerOptions, condition) || this;
  53983. _this.propertyPath = propertyPath;
  53984. _this.value = value;
  53985. _this.duration = duration;
  53986. _this.stopOtherAnimations = stopOtherAnimations;
  53987. _this.onInterpolationDone = onInterpolationDone;
  53988. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53989. _this._target = _this._effectiveTarget = target;
  53990. return _this;
  53991. }
  53992. InterpolateValueAction.prototype._prepare = function () {
  53993. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53994. this._property = this._getProperty(this.propertyPath);
  53995. };
  53996. InterpolateValueAction.prototype.execute = function () {
  53997. var _this = this;
  53998. var scene = this._actionManager.getScene();
  53999. var keys = [
  54000. {
  54001. frame: 0,
  54002. value: this._effectiveTarget[this._property]
  54003. }, {
  54004. frame: 100,
  54005. value: this.value
  54006. }
  54007. ];
  54008. var dataType;
  54009. if (typeof this.value === "number") {
  54010. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54011. }
  54012. else if (this.value instanceof BABYLON.Color3) {
  54013. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54014. }
  54015. else if (this.value instanceof BABYLON.Vector3) {
  54016. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54017. }
  54018. else if (this.value instanceof BABYLON.Matrix) {
  54019. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54020. }
  54021. else if (this.value instanceof BABYLON.Quaternion) {
  54022. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54023. }
  54024. else {
  54025. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54026. return;
  54027. }
  54028. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54029. animation.setKeys(keys);
  54030. if (this.stopOtherAnimations) {
  54031. scene.stopAnimation(this._effectiveTarget);
  54032. }
  54033. var wrapper = function () {
  54034. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54035. if (_this.onInterpolationDone) {
  54036. _this.onInterpolationDone();
  54037. }
  54038. };
  54039. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54040. };
  54041. InterpolateValueAction.prototype.serialize = function (parent) {
  54042. return _super.prototype._serialize.call(this, {
  54043. name: "InterpolateValueAction",
  54044. properties: [
  54045. BABYLON.Action._GetTargetProperty(this._target),
  54046. { name: "propertyPath", value: this.propertyPath },
  54047. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54048. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54049. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54050. ]
  54051. }, parent);
  54052. };
  54053. return InterpolateValueAction;
  54054. }(BABYLON.Action));
  54055. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54056. })(BABYLON || (BABYLON = {}));
  54057. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54058. var BABYLON;
  54059. (function (BABYLON) {
  54060. var SwitchBooleanAction = /** @class */ (function (_super) {
  54061. __extends(SwitchBooleanAction, _super);
  54062. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54063. var _this = _super.call(this, triggerOptions, condition) || this;
  54064. _this.propertyPath = propertyPath;
  54065. _this._target = _this._effectiveTarget = target;
  54066. return _this;
  54067. }
  54068. SwitchBooleanAction.prototype._prepare = function () {
  54069. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54070. this._property = this._getProperty(this.propertyPath);
  54071. };
  54072. SwitchBooleanAction.prototype.execute = function () {
  54073. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54074. };
  54075. SwitchBooleanAction.prototype.serialize = function (parent) {
  54076. return _super.prototype._serialize.call(this, {
  54077. name: "SwitchBooleanAction",
  54078. properties: [
  54079. BABYLON.Action._GetTargetProperty(this._target),
  54080. { name: "propertyPath", value: this.propertyPath }
  54081. ]
  54082. }, parent);
  54083. };
  54084. return SwitchBooleanAction;
  54085. }(BABYLON.Action));
  54086. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54087. var SetStateAction = /** @class */ (function (_super) {
  54088. __extends(SetStateAction, _super);
  54089. function SetStateAction(triggerOptions, target, value, condition) {
  54090. var _this = _super.call(this, triggerOptions, condition) || this;
  54091. _this.value = value;
  54092. _this._target = target;
  54093. return _this;
  54094. }
  54095. SetStateAction.prototype.execute = function () {
  54096. this._target.state = this.value;
  54097. };
  54098. SetStateAction.prototype.serialize = function (parent) {
  54099. return _super.prototype._serialize.call(this, {
  54100. name: "SetStateAction",
  54101. properties: [
  54102. BABYLON.Action._GetTargetProperty(this._target),
  54103. { name: "value", value: this.value }
  54104. ]
  54105. }, parent);
  54106. };
  54107. return SetStateAction;
  54108. }(BABYLON.Action));
  54109. BABYLON.SetStateAction = SetStateAction;
  54110. var SetValueAction = /** @class */ (function (_super) {
  54111. __extends(SetValueAction, _super);
  54112. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54113. var _this = _super.call(this, triggerOptions, condition) || this;
  54114. _this.propertyPath = propertyPath;
  54115. _this.value = value;
  54116. _this._target = _this._effectiveTarget = target;
  54117. return _this;
  54118. }
  54119. SetValueAction.prototype._prepare = function () {
  54120. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54121. this._property = this._getProperty(this.propertyPath);
  54122. };
  54123. SetValueAction.prototype.execute = function () {
  54124. this._effectiveTarget[this._property] = this.value;
  54125. if (this._target.markAsDirty) {
  54126. this._target.markAsDirty(this._property);
  54127. }
  54128. };
  54129. SetValueAction.prototype.serialize = function (parent) {
  54130. return _super.prototype._serialize.call(this, {
  54131. name: "SetValueAction",
  54132. properties: [
  54133. BABYLON.Action._GetTargetProperty(this._target),
  54134. { name: "propertyPath", value: this.propertyPath },
  54135. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54136. ]
  54137. }, parent);
  54138. };
  54139. return SetValueAction;
  54140. }(BABYLON.Action));
  54141. BABYLON.SetValueAction = SetValueAction;
  54142. var IncrementValueAction = /** @class */ (function (_super) {
  54143. __extends(IncrementValueAction, _super);
  54144. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54145. var _this = _super.call(this, triggerOptions, condition) || this;
  54146. _this.propertyPath = propertyPath;
  54147. _this.value = value;
  54148. _this._target = _this._effectiveTarget = target;
  54149. return _this;
  54150. }
  54151. IncrementValueAction.prototype._prepare = function () {
  54152. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54153. this._property = this._getProperty(this.propertyPath);
  54154. if (typeof this._effectiveTarget[this._property] !== "number") {
  54155. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54156. }
  54157. };
  54158. IncrementValueAction.prototype.execute = function () {
  54159. this._effectiveTarget[this._property] += this.value;
  54160. if (this._target.markAsDirty) {
  54161. this._target.markAsDirty(this._property);
  54162. }
  54163. };
  54164. IncrementValueAction.prototype.serialize = function (parent) {
  54165. return _super.prototype._serialize.call(this, {
  54166. name: "IncrementValueAction",
  54167. properties: [
  54168. BABYLON.Action._GetTargetProperty(this._target),
  54169. { name: "propertyPath", value: this.propertyPath },
  54170. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54171. ]
  54172. }, parent);
  54173. };
  54174. return IncrementValueAction;
  54175. }(BABYLON.Action));
  54176. BABYLON.IncrementValueAction = IncrementValueAction;
  54177. var PlayAnimationAction = /** @class */ (function (_super) {
  54178. __extends(PlayAnimationAction, _super);
  54179. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54180. var _this = _super.call(this, triggerOptions, condition) || this;
  54181. _this.from = from;
  54182. _this.to = to;
  54183. _this.loop = loop;
  54184. _this._target = target;
  54185. return _this;
  54186. }
  54187. PlayAnimationAction.prototype._prepare = function () {
  54188. };
  54189. PlayAnimationAction.prototype.execute = function () {
  54190. var scene = this._actionManager.getScene();
  54191. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54192. };
  54193. PlayAnimationAction.prototype.serialize = function (parent) {
  54194. return _super.prototype._serialize.call(this, {
  54195. name: "PlayAnimationAction",
  54196. properties: [
  54197. BABYLON.Action._GetTargetProperty(this._target),
  54198. { name: "from", value: String(this.from) },
  54199. { name: "to", value: String(this.to) },
  54200. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54201. ]
  54202. }, parent);
  54203. };
  54204. return PlayAnimationAction;
  54205. }(BABYLON.Action));
  54206. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54207. var StopAnimationAction = /** @class */ (function (_super) {
  54208. __extends(StopAnimationAction, _super);
  54209. function StopAnimationAction(triggerOptions, target, condition) {
  54210. var _this = _super.call(this, triggerOptions, condition) || this;
  54211. _this._target = target;
  54212. return _this;
  54213. }
  54214. StopAnimationAction.prototype._prepare = function () {
  54215. };
  54216. StopAnimationAction.prototype.execute = function () {
  54217. var scene = this._actionManager.getScene();
  54218. scene.stopAnimation(this._target);
  54219. };
  54220. StopAnimationAction.prototype.serialize = function (parent) {
  54221. return _super.prototype._serialize.call(this, {
  54222. name: "StopAnimationAction",
  54223. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54224. }, parent);
  54225. };
  54226. return StopAnimationAction;
  54227. }(BABYLON.Action));
  54228. BABYLON.StopAnimationAction = StopAnimationAction;
  54229. var DoNothingAction = /** @class */ (function (_super) {
  54230. __extends(DoNothingAction, _super);
  54231. function DoNothingAction(triggerOptions, condition) {
  54232. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54233. return _super.call(this, triggerOptions, condition) || this;
  54234. }
  54235. DoNothingAction.prototype.execute = function () {
  54236. };
  54237. DoNothingAction.prototype.serialize = function (parent) {
  54238. return _super.prototype._serialize.call(this, {
  54239. name: "DoNothingAction",
  54240. properties: []
  54241. }, parent);
  54242. };
  54243. return DoNothingAction;
  54244. }(BABYLON.Action));
  54245. BABYLON.DoNothingAction = DoNothingAction;
  54246. var CombineAction = /** @class */ (function (_super) {
  54247. __extends(CombineAction, _super);
  54248. function CombineAction(triggerOptions, children, condition) {
  54249. var _this = _super.call(this, triggerOptions, condition) || this;
  54250. _this.children = children;
  54251. return _this;
  54252. }
  54253. CombineAction.prototype._prepare = function () {
  54254. for (var index = 0; index < this.children.length; index++) {
  54255. this.children[index]._actionManager = this._actionManager;
  54256. this.children[index]._prepare();
  54257. }
  54258. };
  54259. CombineAction.prototype.execute = function (evt) {
  54260. for (var index = 0; index < this.children.length; index++) {
  54261. this.children[index].execute(evt);
  54262. }
  54263. };
  54264. CombineAction.prototype.serialize = function (parent) {
  54265. var serializationObject = _super.prototype._serialize.call(this, {
  54266. name: "CombineAction",
  54267. properties: [],
  54268. combine: []
  54269. }, parent);
  54270. for (var i = 0; i < this.children.length; i++) {
  54271. serializationObject.combine.push(this.children[i].serialize(null));
  54272. }
  54273. return serializationObject;
  54274. };
  54275. return CombineAction;
  54276. }(BABYLON.Action));
  54277. BABYLON.CombineAction = CombineAction;
  54278. var ExecuteCodeAction = /** @class */ (function (_super) {
  54279. __extends(ExecuteCodeAction, _super);
  54280. function ExecuteCodeAction(triggerOptions, func, condition) {
  54281. var _this = _super.call(this, triggerOptions, condition) || this;
  54282. _this.func = func;
  54283. return _this;
  54284. }
  54285. ExecuteCodeAction.prototype.execute = function (evt) {
  54286. this.func(evt);
  54287. };
  54288. return ExecuteCodeAction;
  54289. }(BABYLON.Action));
  54290. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54291. var SetParentAction = /** @class */ (function (_super) {
  54292. __extends(SetParentAction, _super);
  54293. function SetParentAction(triggerOptions, target, parent, condition) {
  54294. var _this = _super.call(this, triggerOptions, condition) || this;
  54295. _this._target = target;
  54296. _this._parent = parent;
  54297. return _this;
  54298. }
  54299. SetParentAction.prototype._prepare = function () {
  54300. };
  54301. SetParentAction.prototype.execute = function () {
  54302. if (this._target.parent === this._parent) {
  54303. return;
  54304. }
  54305. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54306. invertParentWorldMatrix.invert();
  54307. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54308. this._target.parent = this._parent;
  54309. };
  54310. SetParentAction.prototype.serialize = function (parent) {
  54311. return _super.prototype._serialize.call(this, {
  54312. name: "SetParentAction",
  54313. properties: [
  54314. BABYLON.Action._GetTargetProperty(this._target),
  54315. BABYLON.Action._GetTargetProperty(this._parent),
  54316. ]
  54317. }, parent);
  54318. };
  54319. return SetParentAction;
  54320. }(BABYLON.Action));
  54321. BABYLON.SetParentAction = SetParentAction;
  54322. var PlaySoundAction = /** @class */ (function (_super) {
  54323. __extends(PlaySoundAction, _super);
  54324. function PlaySoundAction(triggerOptions, sound, condition) {
  54325. var _this = _super.call(this, triggerOptions, condition) || this;
  54326. _this._sound = sound;
  54327. return _this;
  54328. }
  54329. PlaySoundAction.prototype._prepare = function () {
  54330. };
  54331. PlaySoundAction.prototype.execute = function () {
  54332. if (this._sound !== undefined)
  54333. this._sound.play();
  54334. };
  54335. PlaySoundAction.prototype.serialize = function (parent) {
  54336. return _super.prototype._serialize.call(this, {
  54337. name: "PlaySoundAction",
  54338. properties: [{ name: "sound", value: this._sound.name }]
  54339. }, parent);
  54340. };
  54341. return PlaySoundAction;
  54342. }(BABYLON.Action));
  54343. BABYLON.PlaySoundAction = PlaySoundAction;
  54344. var StopSoundAction = /** @class */ (function (_super) {
  54345. __extends(StopSoundAction, _super);
  54346. function StopSoundAction(triggerOptions, sound, condition) {
  54347. var _this = _super.call(this, triggerOptions, condition) || this;
  54348. _this._sound = sound;
  54349. return _this;
  54350. }
  54351. StopSoundAction.prototype._prepare = function () {
  54352. };
  54353. StopSoundAction.prototype.execute = function () {
  54354. if (this._sound !== undefined)
  54355. this._sound.stop();
  54356. };
  54357. StopSoundAction.prototype.serialize = function (parent) {
  54358. return _super.prototype._serialize.call(this, {
  54359. name: "StopSoundAction",
  54360. properties: [{ name: "sound", value: this._sound.name }]
  54361. }, parent);
  54362. };
  54363. return StopSoundAction;
  54364. }(BABYLON.Action));
  54365. BABYLON.StopSoundAction = StopSoundAction;
  54366. })(BABYLON || (BABYLON = {}));
  54367. //# sourceMappingURL=babylon.directActions.js.map
  54368. var BABYLON;
  54369. (function (BABYLON) {
  54370. var SpriteManager = /** @class */ (function () {
  54371. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54372. if (epsilon === void 0) { epsilon = 0.01; }
  54373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54374. this.name = name;
  54375. this.sprites = new Array();
  54376. this.renderingGroupId = 0;
  54377. this.layerMask = 0x0FFFFFFF;
  54378. this.fogEnabled = true;
  54379. this.isPickable = false;
  54380. /**
  54381. * An event triggered when the manager is disposed.
  54382. */
  54383. this.onDisposeObservable = new BABYLON.Observable();
  54384. this._vertexBuffers = {};
  54385. this._capacity = capacity;
  54386. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54387. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54388. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54389. if (cellSize.width && cellSize.height) {
  54390. this.cellWidth = cellSize.width;
  54391. this.cellHeight = cellSize.height;
  54392. }
  54393. else if (cellSize !== undefined) {
  54394. this.cellWidth = cellSize;
  54395. this.cellHeight = cellSize;
  54396. }
  54397. else {
  54398. return;
  54399. }
  54400. this._epsilon = epsilon;
  54401. this._scene = scene;
  54402. this._scene.spriteManagers.push(this);
  54403. var indices = [];
  54404. var index = 0;
  54405. for (var count = 0; count < capacity; count++) {
  54406. indices.push(index);
  54407. indices.push(index + 1);
  54408. indices.push(index + 2);
  54409. indices.push(index);
  54410. indices.push(index + 2);
  54411. indices.push(index + 3);
  54412. index += 4;
  54413. }
  54414. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54415. // VBO
  54416. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54417. this._vertexData = new Float32Array(capacity * 16 * 4);
  54418. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54419. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54420. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54421. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54422. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54424. this._vertexBuffers["options"] = options;
  54425. this._vertexBuffers["cellInfo"] = cellInfo;
  54426. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54427. // Effects
  54428. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54429. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54430. }
  54431. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54432. set: function (callback) {
  54433. if (this._onDisposeObserver) {
  54434. this.onDisposeObservable.remove(this._onDisposeObserver);
  54435. }
  54436. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54437. },
  54438. enumerable: true,
  54439. configurable: true
  54440. });
  54441. Object.defineProperty(SpriteManager.prototype, "texture", {
  54442. get: function () {
  54443. return this._spriteTexture;
  54444. },
  54445. set: function (value) {
  54446. this._spriteTexture = value;
  54447. },
  54448. enumerable: true,
  54449. configurable: true
  54450. });
  54451. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54452. var arrayOffset = index * 16;
  54453. if (offsetX === 0)
  54454. offsetX = this._epsilon;
  54455. else if (offsetX === 1)
  54456. offsetX = 1 - this._epsilon;
  54457. if (offsetY === 0)
  54458. offsetY = this._epsilon;
  54459. else if (offsetY === 1)
  54460. offsetY = 1 - this._epsilon;
  54461. this._vertexData[arrayOffset] = sprite.position.x;
  54462. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54463. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54464. this._vertexData[arrayOffset + 3] = sprite.angle;
  54465. this._vertexData[arrayOffset + 4] = sprite.width;
  54466. this._vertexData[arrayOffset + 5] = sprite.height;
  54467. this._vertexData[arrayOffset + 6] = offsetX;
  54468. this._vertexData[arrayOffset + 7] = offsetY;
  54469. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54470. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54471. var offset = (sprite.cellIndex / rowSize) >> 0;
  54472. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54473. this._vertexData[arrayOffset + 11] = offset;
  54474. // Color
  54475. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54476. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54477. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54478. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54479. };
  54480. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54481. var count = Math.min(this._capacity, this.sprites.length);
  54482. var min = BABYLON.Vector3.Zero();
  54483. var max = BABYLON.Vector3.Zero();
  54484. var distance = Number.MAX_VALUE;
  54485. var currentSprite = null;
  54486. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54487. var cameraView = camera.getViewMatrix();
  54488. for (var index = 0; index < count; index++) {
  54489. var sprite = this.sprites[index];
  54490. if (!sprite) {
  54491. continue;
  54492. }
  54493. if (predicate) {
  54494. if (!predicate(sprite)) {
  54495. continue;
  54496. }
  54497. }
  54498. else if (!sprite.isPickable) {
  54499. continue;
  54500. }
  54501. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54502. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54503. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54504. if (ray.intersectsBoxMinMax(min, max)) {
  54505. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54506. if (distance > currentDistance) {
  54507. distance = currentDistance;
  54508. currentSprite = sprite;
  54509. if (fastCheck) {
  54510. break;
  54511. }
  54512. }
  54513. }
  54514. }
  54515. if (currentSprite) {
  54516. var result = new BABYLON.PickingInfo();
  54517. result.hit = true;
  54518. result.pickedSprite = currentSprite;
  54519. result.distance = distance;
  54520. return result;
  54521. }
  54522. return null;
  54523. };
  54524. SpriteManager.prototype.render = function () {
  54525. // Check
  54526. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54527. return;
  54528. var engine = this._scene.getEngine();
  54529. var baseSize = this._spriteTexture.getBaseSize();
  54530. // Sprites
  54531. var deltaTime = engine.getDeltaTime();
  54532. var max = Math.min(this._capacity, this.sprites.length);
  54533. var rowSize = baseSize.width / this.cellWidth;
  54534. var offset = 0;
  54535. for (var index = 0; index < max; index++) {
  54536. var sprite = this.sprites[index];
  54537. if (!sprite) {
  54538. continue;
  54539. }
  54540. sprite._animate(deltaTime);
  54541. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54542. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54543. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54544. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54545. }
  54546. this._buffer.update(this._vertexData);
  54547. // Render
  54548. var effect = this._effectBase;
  54549. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54550. effect = this._effectFog;
  54551. }
  54552. engine.enableEffect(effect);
  54553. var viewMatrix = this._scene.getViewMatrix();
  54554. effect.setTexture("diffuseSampler", this._spriteTexture);
  54555. effect.setMatrix("view", viewMatrix);
  54556. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54557. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54558. // Fog
  54559. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54560. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54561. effect.setColor3("vFogColor", this._scene.fogColor);
  54562. }
  54563. // VBOs
  54564. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54565. // Draw order
  54566. engine.setDepthFunctionToLessOrEqual();
  54567. effect.setBool("alphaTest", true);
  54568. engine.setColorWrite(false);
  54569. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54570. engine.setColorWrite(true);
  54571. effect.setBool("alphaTest", false);
  54572. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54573. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54574. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54575. };
  54576. SpriteManager.prototype.dispose = function () {
  54577. if (this._buffer) {
  54578. this._buffer.dispose();
  54579. this._buffer = null;
  54580. }
  54581. if (this._indexBuffer) {
  54582. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54583. this._indexBuffer = null;
  54584. }
  54585. if (this._spriteTexture) {
  54586. this._spriteTexture.dispose();
  54587. this._spriteTexture = null;
  54588. }
  54589. // Remove from scene
  54590. var index = this._scene.spriteManagers.indexOf(this);
  54591. this._scene.spriteManagers.splice(index, 1);
  54592. // Callback
  54593. this.onDisposeObservable.notifyObservers(this);
  54594. this.onDisposeObservable.clear();
  54595. };
  54596. return SpriteManager;
  54597. }());
  54598. BABYLON.SpriteManager = SpriteManager;
  54599. })(BABYLON || (BABYLON = {}));
  54600. //# sourceMappingURL=babylon.spriteManager.js.map
  54601. var BABYLON;
  54602. (function (BABYLON) {
  54603. var Sprite = /** @class */ (function () {
  54604. function Sprite(name, manager) {
  54605. this.name = name;
  54606. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54607. this.width = 1.0;
  54608. this.height = 1.0;
  54609. this.angle = 0;
  54610. this.cellIndex = 0;
  54611. this.invertU = 0;
  54612. this.invertV = 0;
  54613. this.animations = new Array();
  54614. this.isPickable = false;
  54615. this._animationStarted = false;
  54616. this._loopAnimation = false;
  54617. this._fromIndex = 0;
  54618. this._toIndex = 0;
  54619. this._delay = 0;
  54620. this._direction = 1;
  54621. this._time = 0;
  54622. this._manager = manager;
  54623. this._manager.sprites.push(this);
  54624. this.position = BABYLON.Vector3.Zero();
  54625. }
  54626. Object.defineProperty(Sprite.prototype, "size", {
  54627. get: function () {
  54628. return this.width;
  54629. },
  54630. set: function (value) {
  54631. this.width = value;
  54632. this.height = value;
  54633. },
  54634. enumerable: true,
  54635. configurable: true
  54636. });
  54637. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54638. this._fromIndex = from;
  54639. this._toIndex = to;
  54640. this._loopAnimation = loop;
  54641. this._delay = delay;
  54642. this._animationStarted = true;
  54643. this._direction = from < to ? 1 : -1;
  54644. this.cellIndex = from;
  54645. this._time = 0;
  54646. this._onAnimationEnd = onAnimationEnd;
  54647. };
  54648. Sprite.prototype.stopAnimation = function () {
  54649. this._animationStarted = false;
  54650. };
  54651. Sprite.prototype._animate = function (deltaTime) {
  54652. if (!this._animationStarted)
  54653. return;
  54654. this._time += deltaTime;
  54655. if (this._time > this._delay) {
  54656. this._time = this._time % this._delay;
  54657. this.cellIndex += this._direction;
  54658. if (this.cellIndex > this._toIndex) {
  54659. if (this._loopAnimation) {
  54660. this.cellIndex = this._fromIndex;
  54661. }
  54662. else {
  54663. this.cellIndex = this._toIndex;
  54664. this._animationStarted = false;
  54665. if (this._onAnimationEnd) {
  54666. this._onAnimationEnd();
  54667. }
  54668. if (this.disposeWhenFinishedAnimating) {
  54669. this.dispose();
  54670. }
  54671. }
  54672. }
  54673. }
  54674. };
  54675. Sprite.prototype.dispose = function () {
  54676. for (var i = 0; i < this._manager.sprites.length; i++) {
  54677. if (this._manager.sprites[i] == this) {
  54678. this._manager.sprites.splice(i, 1);
  54679. }
  54680. }
  54681. };
  54682. return Sprite;
  54683. }());
  54684. BABYLON.Sprite = Sprite;
  54685. })(BABYLON || (BABYLON = {}));
  54686. //# sourceMappingURL=babylon.sprite.js.map
  54687. var BABYLON;
  54688. (function (BABYLON) {
  54689. var IntersectionInfo = /** @class */ (function () {
  54690. function IntersectionInfo(bu, bv, distance) {
  54691. this.bu = bu;
  54692. this.bv = bv;
  54693. this.distance = distance;
  54694. this.faceId = 0;
  54695. this.subMeshId = 0;
  54696. }
  54697. return IntersectionInfo;
  54698. }());
  54699. BABYLON.IntersectionInfo = IntersectionInfo;
  54700. var PickingInfo = /** @class */ (function () {
  54701. function PickingInfo() {
  54702. this.hit = false;
  54703. this.distance = 0;
  54704. this.pickedPoint = null;
  54705. this.pickedMesh = null;
  54706. this.bu = 0;
  54707. this.bv = 0;
  54708. this.faceId = -1;
  54709. this.subMeshId = 0;
  54710. this.pickedSprite = null;
  54711. }
  54712. // Methods
  54713. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54714. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54715. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54716. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54717. return null;
  54718. }
  54719. var indices = this.pickedMesh.getIndices();
  54720. if (!indices) {
  54721. return null;
  54722. }
  54723. var result;
  54724. if (useVerticesNormals) {
  54725. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54726. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54727. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54728. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54729. normal0 = normal0.scale(this.bu);
  54730. normal1 = normal1.scale(this.bv);
  54731. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54732. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54733. }
  54734. else {
  54735. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54736. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54737. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54738. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54739. var p1p2 = vertex1.subtract(vertex2);
  54740. var p3p2 = vertex3.subtract(vertex2);
  54741. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54742. }
  54743. if (useWorldCoordinates) {
  54744. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54745. }
  54746. return BABYLON.Vector3.Normalize(result);
  54747. };
  54748. PickingInfo.prototype.getTextureCoordinates = function () {
  54749. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54750. return null;
  54751. }
  54752. var indices = this.pickedMesh.getIndices();
  54753. if (!indices) {
  54754. return null;
  54755. }
  54756. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54757. if (!uvs) {
  54758. return null;
  54759. }
  54760. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54761. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54762. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54763. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54764. uv1 = uv1.scale(this.bu);
  54765. uv2 = uv2.scale(this.bv);
  54766. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54767. };
  54768. return PickingInfo;
  54769. }());
  54770. BABYLON.PickingInfo = PickingInfo;
  54771. })(BABYLON || (BABYLON = {}));
  54772. //# sourceMappingURL=babylon.pickingInfo.js.map
  54773. var BABYLON;
  54774. (function (BABYLON) {
  54775. var Ray = /** @class */ (function () {
  54776. function Ray(origin, direction, length) {
  54777. if (length === void 0) { length = Number.MAX_VALUE; }
  54778. this.origin = origin;
  54779. this.direction = direction;
  54780. this.length = length;
  54781. }
  54782. // Methods
  54783. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54784. var d = 0.0;
  54785. var maxValue = Number.MAX_VALUE;
  54786. var inv;
  54787. var min;
  54788. var max;
  54789. var temp;
  54790. if (Math.abs(this.direction.x) < 0.0000001) {
  54791. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54792. return false;
  54793. }
  54794. }
  54795. else {
  54796. inv = 1.0 / this.direction.x;
  54797. min = (minimum.x - this.origin.x) * inv;
  54798. max = (maximum.x - this.origin.x) * inv;
  54799. if (max === -Infinity) {
  54800. max = Infinity;
  54801. }
  54802. if (min > max) {
  54803. temp = min;
  54804. min = max;
  54805. max = temp;
  54806. }
  54807. d = Math.max(min, d);
  54808. maxValue = Math.min(max, maxValue);
  54809. if (d > maxValue) {
  54810. return false;
  54811. }
  54812. }
  54813. if (Math.abs(this.direction.y) < 0.0000001) {
  54814. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54815. return false;
  54816. }
  54817. }
  54818. else {
  54819. inv = 1.0 / this.direction.y;
  54820. min = (minimum.y - this.origin.y) * inv;
  54821. max = (maximum.y - this.origin.y) * inv;
  54822. if (max === -Infinity) {
  54823. max = Infinity;
  54824. }
  54825. if (min > max) {
  54826. temp = min;
  54827. min = max;
  54828. max = temp;
  54829. }
  54830. d = Math.max(min, d);
  54831. maxValue = Math.min(max, maxValue);
  54832. if (d > maxValue) {
  54833. return false;
  54834. }
  54835. }
  54836. if (Math.abs(this.direction.z) < 0.0000001) {
  54837. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54838. return false;
  54839. }
  54840. }
  54841. else {
  54842. inv = 1.0 / this.direction.z;
  54843. min = (minimum.z - this.origin.z) * inv;
  54844. max = (maximum.z - this.origin.z) * inv;
  54845. if (max === -Infinity) {
  54846. max = Infinity;
  54847. }
  54848. if (min > max) {
  54849. temp = min;
  54850. min = max;
  54851. max = temp;
  54852. }
  54853. d = Math.max(min, d);
  54854. maxValue = Math.min(max, maxValue);
  54855. if (d > maxValue) {
  54856. return false;
  54857. }
  54858. }
  54859. return true;
  54860. };
  54861. Ray.prototype.intersectsBox = function (box) {
  54862. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54863. };
  54864. Ray.prototype.intersectsSphere = function (sphere) {
  54865. var x = sphere.center.x - this.origin.x;
  54866. var y = sphere.center.y - this.origin.y;
  54867. var z = sphere.center.z - this.origin.z;
  54868. var pyth = (x * x) + (y * y) + (z * z);
  54869. var rr = sphere.radius * sphere.radius;
  54870. if (pyth <= rr) {
  54871. return true;
  54872. }
  54873. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54874. if (dot < 0.0) {
  54875. return false;
  54876. }
  54877. var temp = pyth - (dot * dot);
  54878. return temp <= rr;
  54879. };
  54880. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54881. if (!this._edge1) {
  54882. this._edge1 = BABYLON.Vector3.Zero();
  54883. this._edge2 = BABYLON.Vector3.Zero();
  54884. this._pvec = BABYLON.Vector3.Zero();
  54885. this._tvec = BABYLON.Vector3.Zero();
  54886. this._qvec = BABYLON.Vector3.Zero();
  54887. }
  54888. vertex1.subtractToRef(vertex0, this._edge1);
  54889. vertex2.subtractToRef(vertex0, this._edge2);
  54890. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54891. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54892. if (det === 0) {
  54893. return null;
  54894. }
  54895. var invdet = 1 / det;
  54896. this.origin.subtractToRef(vertex0, this._tvec);
  54897. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54898. if (bu < 0 || bu > 1.0) {
  54899. return null;
  54900. }
  54901. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54902. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54903. if (bv < 0 || bu + bv > 1.0) {
  54904. return null;
  54905. }
  54906. //check if the distance is longer than the predefined length.
  54907. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54908. if (distance > this.length) {
  54909. return null;
  54910. }
  54911. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54912. };
  54913. Ray.prototype.intersectsPlane = function (plane) {
  54914. var distance;
  54915. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54916. if (Math.abs(result1) < 9.99999997475243E-07) {
  54917. return null;
  54918. }
  54919. else {
  54920. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54921. distance = (-plane.d - result2) / result1;
  54922. if (distance < 0.0) {
  54923. if (distance < -9.99999997475243E-07) {
  54924. return null;
  54925. }
  54926. else {
  54927. return 0;
  54928. }
  54929. }
  54930. return distance;
  54931. }
  54932. };
  54933. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54934. var tm = BABYLON.Tmp.Matrix[0];
  54935. mesh.getWorldMatrix().invertToRef(tm);
  54936. if (this._tmpRay) {
  54937. Ray.TransformToRef(this, tm, this._tmpRay);
  54938. }
  54939. else {
  54940. this._tmpRay = Ray.Transform(this, tm);
  54941. }
  54942. return mesh.intersects(this._tmpRay, fastCheck);
  54943. };
  54944. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54945. if (results) {
  54946. results.length = 0;
  54947. }
  54948. else {
  54949. results = [];
  54950. }
  54951. for (var i = 0; i < meshes.length; i++) {
  54952. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54953. if (pickInfo.hit) {
  54954. results.push(pickInfo);
  54955. }
  54956. }
  54957. results.sort(this._comparePickingInfo);
  54958. return results;
  54959. };
  54960. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54961. if (pickingInfoA.distance < pickingInfoB.distance) {
  54962. return -1;
  54963. }
  54964. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54965. return 1;
  54966. }
  54967. else {
  54968. return 0;
  54969. }
  54970. };
  54971. /**
  54972. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54973. * @param sega the first point of the segment to test the intersection against
  54974. * @param segb the second point of the segment to test the intersection against
  54975. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54976. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54977. */
  54978. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54979. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54980. var u = segb.subtract(sega);
  54981. var v = rsegb.subtract(this.origin);
  54982. var w = sega.subtract(this.origin);
  54983. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54984. var b = BABYLON.Vector3.Dot(u, v);
  54985. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54986. var d = BABYLON.Vector3.Dot(u, w);
  54987. var e = BABYLON.Vector3.Dot(v, w);
  54988. var D = a * c - b * b; // always >= 0
  54989. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54990. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54991. // compute the line parameters of the two closest points
  54992. if (D < Ray.smallnum) { // the lines are almost parallel
  54993. sN = 0.0; // force using point P0 on segment S1
  54994. sD = 1.0; // to prevent possible division by 0.0 later
  54995. tN = e;
  54996. tD = c;
  54997. }
  54998. else { // get the closest points on the infinite lines
  54999. sN = (b * e - c * d);
  55000. tN = (a * e - b * d);
  55001. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55002. sN = 0.0;
  55003. tN = e;
  55004. tD = c;
  55005. }
  55006. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55007. sN = sD;
  55008. tN = e + b;
  55009. tD = c;
  55010. }
  55011. }
  55012. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55013. tN = 0.0;
  55014. // recompute sc for this edge
  55015. if (-d < 0.0) {
  55016. sN = 0.0;
  55017. }
  55018. else if (-d > a)
  55019. sN = sD;
  55020. else {
  55021. sN = -d;
  55022. sD = a;
  55023. }
  55024. }
  55025. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55026. tN = tD;
  55027. // recompute sc for this edge
  55028. if ((-d + b) < 0.0) {
  55029. sN = 0;
  55030. }
  55031. else if ((-d + b) > a) {
  55032. sN = sD;
  55033. }
  55034. else {
  55035. sN = (-d + b);
  55036. sD = a;
  55037. }
  55038. }
  55039. // finally do the division to get sc and tc
  55040. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55041. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55042. // get the difference of the two closest points
  55043. var qtc = v.multiplyByFloats(tc, tc, tc);
  55044. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55045. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55046. if (isIntersected) {
  55047. return qtc.length();
  55048. }
  55049. return -1;
  55050. };
  55051. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55052. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55053. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55054. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55055. this.direction.normalize();
  55056. return this;
  55057. };
  55058. // Statics
  55059. Ray.Zero = function () {
  55060. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55061. };
  55062. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55063. var result = Ray.Zero();
  55064. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55065. };
  55066. /**
  55067. * 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
  55068. * transformed to the given world matrix.
  55069. * @param origin The origin point
  55070. * @param end The end point
  55071. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55072. */
  55073. Ray.CreateNewFromTo = function (origin, end, world) {
  55074. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55075. var direction = end.subtract(origin);
  55076. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55077. direction.normalize();
  55078. return Ray.Transform(new Ray(origin, direction, length), world);
  55079. };
  55080. Ray.Transform = function (ray, matrix) {
  55081. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55082. Ray.TransformToRef(ray, matrix, result);
  55083. return result;
  55084. };
  55085. Ray.TransformToRef = function (ray, matrix, result) {
  55086. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55087. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55088. result.length = ray.length;
  55089. var dir = result.direction;
  55090. var len = dir.length();
  55091. if (!(len === 0 || len === 1)) {
  55092. var num = 1.0 / len;
  55093. dir.x *= num;
  55094. dir.y *= num;
  55095. dir.z *= num;
  55096. result.length *= len;
  55097. }
  55098. };
  55099. Ray.smallnum = 0.00000001;
  55100. Ray.rayl = 10e8;
  55101. return Ray;
  55102. }());
  55103. BABYLON.Ray = Ray;
  55104. })(BABYLON || (BABYLON = {}));
  55105. //# sourceMappingURL=babylon.ray.js.map
  55106. var BABYLON;
  55107. (function (BABYLON) {
  55108. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55109. if (boxMin.x > sphereCenter.x + sphereRadius)
  55110. return false;
  55111. if (sphereCenter.x - sphereRadius > boxMax.x)
  55112. return false;
  55113. if (boxMin.y > sphereCenter.y + sphereRadius)
  55114. return false;
  55115. if (sphereCenter.y - sphereRadius > boxMax.y)
  55116. return false;
  55117. if (boxMin.z > sphereCenter.z + sphereRadius)
  55118. return false;
  55119. if (sphereCenter.z - sphereRadius > boxMax.z)
  55120. return false;
  55121. return true;
  55122. };
  55123. var getLowestRoot = (function () {
  55124. var result = { root: 0, found: false };
  55125. return function (a, b, c, maxR) {
  55126. result.root = 0;
  55127. result.found = false;
  55128. var determinant = b * b - 4.0 * a * c;
  55129. if (determinant < 0)
  55130. return result;
  55131. var sqrtD = Math.sqrt(determinant);
  55132. var r1 = (-b - sqrtD) / (2.0 * a);
  55133. var r2 = (-b + sqrtD) / (2.0 * a);
  55134. if (r1 > r2) {
  55135. var temp = r2;
  55136. r2 = r1;
  55137. r1 = temp;
  55138. }
  55139. if (r1 > 0 && r1 < maxR) {
  55140. result.root = r1;
  55141. result.found = true;
  55142. return result;
  55143. }
  55144. if (r2 > 0 && r2 < maxR) {
  55145. result.root = r2;
  55146. result.found = true;
  55147. return result;
  55148. }
  55149. return result;
  55150. };
  55151. })();
  55152. var Collider = /** @class */ (function () {
  55153. function Collider() {
  55154. this._collisionPoint = BABYLON.Vector3.Zero();
  55155. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55156. this._tempVector = BABYLON.Vector3.Zero();
  55157. this._tempVector2 = BABYLON.Vector3.Zero();
  55158. this._tempVector3 = BABYLON.Vector3.Zero();
  55159. this._tempVector4 = BABYLON.Vector3.Zero();
  55160. this._edge = BABYLON.Vector3.Zero();
  55161. this._baseToVertex = BABYLON.Vector3.Zero();
  55162. this._destinationPoint = BABYLON.Vector3.Zero();
  55163. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55164. this._displacementVector = BABYLON.Vector3.Zero();
  55165. this._radius = BABYLON.Vector3.One();
  55166. this._retry = 0;
  55167. this._basePointWorld = BABYLON.Vector3.Zero();
  55168. this._velocityWorld = BABYLON.Vector3.Zero();
  55169. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55170. this._collisionMask = -1;
  55171. }
  55172. Object.defineProperty(Collider.prototype, "collisionMask", {
  55173. get: function () {
  55174. return this._collisionMask;
  55175. },
  55176. set: function (mask) {
  55177. this._collisionMask = !isNaN(mask) ? mask : -1;
  55178. },
  55179. enumerable: true,
  55180. configurable: true
  55181. });
  55182. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55183. /**
  55184. * Gets the plane normal used to compute the sliding response (in local space)
  55185. */
  55186. get: function () {
  55187. return this._slidePlaneNormal;
  55188. },
  55189. enumerable: true,
  55190. configurable: true
  55191. });
  55192. // Methods
  55193. Collider.prototype._initialize = function (source, dir, e) {
  55194. this._velocity = dir;
  55195. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55196. this._basePoint = source;
  55197. source.multiplyToRef(this._radius, this._basePointWorld);
  55198. dir.multiplyToRef(this._radius, this._velocityWorld);
  55199. this._velocityWorldLength = this._velocityWorld.length();
  55200. this._epsilon = e;
  55201. this.collisionFound = false;
  55202. };
  55203. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55204. pa.subtractToRef(point, this._tempVector);
  55205. pb.subtractToRef(point, this._tempVector2);
  55206. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55207. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55208. if (d < 0)
  55209. return false;
  55210. pc.subtractToRef(point, this._tempVector3);
  55211. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55212. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55213. if (d < 0)
  55214. return false;
  55215. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55216. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55217. return d >= 0;
  55218. };
  55219. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55220. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55221. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55222. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55223. return false;
  55224. }
  55225. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55226. return false;
  55227. return true;
  55228. };
  55229. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55230. var t0;
  55231. var embeddedInPlane = false;
  55232. //defensive programming, actually not needed.
  55233. if (!trianglePlaneArray) {
  55234. trianglePlaneArray = [];
  55235. }
  55236. if (!trianglePlaneArray[faceIndex]) {
  55237. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55238. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55239. }
  55240. var trianglePlane = trianglePlaneArray[faceIndex];
  55241. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55242. return;
  55243. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55244. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55245. if (normalDotVelocity == 0) {
  55246. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55247. return;
  55248. embeddedInPlane = true;
  55249. t0 = 0;
  55250. }
  55251. else {
  55252. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55253. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55254. if (t0 > t1) {
  55255. var temp = t1;
  55256. t1 = t0;
  55257. t0 = temp;
  55258. }
  55259. if (t0 > 1.0 || t1 < 0.0)
  55260. return;
  55261. if (t0 < 0)
  55262. t0 = 0;
  55263. if (t0 > 1.0)
  55264. t0 = 1.0;
  55265. }
  55266. this._collisionPoint.copyFromFloats(0, 0, 0);
  55267. var found = false;
  55268. var t = 1.0;
  55269. if (!embeddedInPlane) {
  55270. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55271. this._velocity.scaleToRef(t0, this._tempVector);
  55272. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55273. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55274. found = true;
  55275. t = t0;
  55276. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55277. }
  55278. }
  55279. if (!found) {
  55280. var velocitySquaredLength = this._velocity.lengthSquared();
  55281. var a = velocitySquaredLength;
  55282. this._basePoint.subtractToRef(p1, this._tempVector);
  55283. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55284. var c = this._tempVector.lengthSquared() - 1.0;
  55285. var lowestRoot = getLowestRoot(a, b, c, t);
  55286. if (lowestRoot.found) {
  55287. t = lowestRoot.root;
  55288. found = true;
  55289. this._collisionPoint.copyFrom(p1);
  55290. }
  55291. this._basePoint.subtractToRef(p2, this._tempVector);
  55292. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55293. c = this._tempVector.lengthSquared() - 1.0;
  55294. lowestRoot = getLowestRoot(a, b, c, t);
  55295. if (lowestRoot.found) {
  55296. t = lowestRoot.root;
  55297. found = true;
  55298. this._collisionPoint.copyFrom(p2);
  55299. }
  55300. this._basePoint.subtractToRef(p3, this._tempVector);
  55301. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55302. c = this._tempVector.lengthSquared() - 1.0;
  55303. lowestRoot = getLowestRoot(a, b, c, t);
  55304. if (lowestRoot.found) {
  55305. t = lowestRoot.root;
  55306. found = true;
  55307. this._collisionPoint.copyFrom(p3);
  55308. }
  55309. p2.subtractToRef(p1, this._edge);
  55310. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55311. var edgeSquaredLength = this._edge.lengthSquared();
  55312. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55313. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55314. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55315. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55316. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55317. lowestRoot = getLowestRoot(a, b, c, t);
  55318. if (lowestRoot.found) {
  55319. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55320. if (f >= 0.0 && f <= 1.0) {
  55321. t = lowestRoot.root;
  55322. found = true;
  55323. this._edge.scaleInPlace(f);
  55324. p1.addToRef(this._edge, this._collisionPoint);
  55325. }
  55326. }
  55327. p3.subtractToRef(p2, this._edge);
  55328. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55329. edgeSquaredLength = this._edge.lengthSquared();
  55330. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55331. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55332. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55333. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55334. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55335. lowestRoot = getLowestRoot(a, b, c, t);
  55336. if (lowestRoot.found) {
  55337. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55338. if (f >= 0.0 && f <= 1.0) {
  55339. t = lowestRoot.root;
  55340. found = true;
  55341. this._edge.scaleInPlace(f);
  55342. p2.addToRef(this._edge, this._collisionPoint);
  55343. }
  55344. }
  55345. p1.subtractToRef(p3, this._edge);
  55346. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55347. edgeSquaredLength = this._edge.lengthSquared();
  55348. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55349. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55350. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55351. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55352. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55353. lowestRoot = getLowestRoot(a, b, c, t);
  55354. if (lowestRoot.found) {
  55355. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55356. if (f >= 0.0 && f <= 1.0) {
  55357. t = lowestRoot.root;
  55358. found = true;
  55359. this._edge.scaleInPlace(f);
  55360. p3.addToRef(this._edge, this._collisionPoint);
  55361. }
  55362. }
  55363. }
  55364. if (found) {
  55365. var distToCollision = t * this._velocity.length();
  55366. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55367. if (!this.intersectionPoint) {
  55368. this.intersectionPoint = this._collisionPoint.clone();
  55369. }
  55370. else {
  55371. this.intersectionPoint.copyFrom(this._collisionPoint);
  55372. }
  55373. this._nearestDistance = distToCollision;
  55374. this.collisionFound = true;
  55375. }
  55376. }
  55377. };
  55378. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55379. for (var i = indexStart; i < indexEnd; i += 3) {
  55380. var p1 = pts[indices[i] - decal];
  55381. var p2 = pts[indices[i + 1] - decal];
  55382. var p3 = pts[indices[i + 2] - decal];
  55383. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55384. }
  55385. };
  55386. Collider.prototype._getResponse = function (pos, vel) {
  55387. pos.addToRef(vel, this._destinationPoint);
  55388. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55389. this._basePoint.addToRef(vel, pos);
  55390. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55391. this._slidePlaneNormal.normalize();
  55392. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55393. pos.addInPlace(this._displacementVector);
  55394. this.intersectionPoint.addInPlace(this._displacementVector);
  55395. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55396. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55397. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55398. };
  55399. return Collider;
  55400. }());
  55401. BABYLON.Collider = Collider;
  55402. })(BABYLON || (BABYLON = {}));
  55403. //# sourceMappingURL=babylon.collider.js.map
  55404. var BABYLON;
  55405. (function (BABYLON) {
  55406. //WebWorker code will be inserted to this variable.
  55407. BABYLON.CollisionWorker = "";
  55408. /** Defines supported task for worker process */
  55409. var WorkerTaskType;
  55410. (function (WorkerTaskType) {
  55411. /** Initialization */
  55412. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55413. /** Update of geometry */
  55414. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55415. /** Evaluate collision */
  55416. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55417. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55418. /** Defines kind of replies returned by worker */
  55419. var WorkerReplyType;
  55420. (function (WorkerReplyType) {
  55421. /** Success */
  55422. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55423. /** Unkown error */
  55424. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55425. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55426. var CollisionCoordinatorWorker = /** @class */ (function () {
  55427. function CollisionCoordinatorWorker() {
  55428. var _this = this;
  55429. this._scaledPosition = BABYLON.Vector3.Zero();
  55430. this._scaledVelocity = BABYLON.Vector3.Zero();
  55431. this.onMeshUpdated = function (transformNode) {
  55432. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55433. };
  55434. this.onGeometryUpdated = function (geometry) {
  55435. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55436. };
  55437. this._afterRender = function () {
  55438. if (!_this._init)
  55439. return;
  55440. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55441. return;
  55442. }
  55443. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55444. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55445. if (_this._runningUpdated > 4) {
  55446. return;
  55447. }
  55448. ++_this._runningUpdated;
  55449. var payload = {
  55450. updatedMeshes: _this._addUpdateMeshesList,
  55451. updatedGeometries: _this._addUpdateGeometriesList,
  55452. removedGeometries: _this._toRemoveGeometryArray,
  55453. removedMeshes: _this._toRemoveMeshesArray
  55454. };
  55455. var message = {
  55456. payload: payload,
  55457. taskType: WorkerTaskType.UPDATE
  55458. };
  55459. var serializable = [];
  55460. for (var id in payload.updatedGeometries) {
  55461. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55462. //prepare transferables
  55463. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55464. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55465. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55466. }
  55467. }
  55468. _this._worker.postMessage(message, serializable);
  55469. _this._addUpdateMeshesList = {};
  55470. _this._addUpdateGeometriesList = {};
  55471. _this._toRemoveGeometryArray = [];
  55472. _this._toRemoveMeshesArray = [];
  55473. };
  55474. this._onMessageFromWorker = function (e) {
  55475. var returnData = e.data;
  55476. if (returnData.error != WorkerReplyType.SUCCESS) {
  55477. //TODO what errors can be returned from the worker?
  55478. BABYLON.Tools.Warn("error returned from worker!");
  55479. return;
  55480. }
  55481. switch (returnData.taskType) {
  55482. case WorkerTaskType.INIT:
  55483. _this._init = true;
  55484. //Update the worked with ALL of the scene's current state
  55485. _this._scene.meshes.forEach(function (mesh) {
  55486. _this.onMeshAdded(mesh);
  55487. });
  55488. _this._scene.getGeometries().forEach(function (geometry) {
  55489. _this.onGeometryAdded(geometry);
  55490. });
  55491. break;
  55492. case WorkerTaskType.UPDATE:
  55493. _this._runningUpdated--;
  55494. break;
  55495. case WorkerTaskType.COLLIDE:
  55496. var returnPayload = returnData.payload;
  55497. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55498. return;
  55499. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55500. if (callback) {
  55501. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55502. if (mesh) {
  55503. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55504. }
  55505. }
  55506. //cleanup
  55507. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55508. break;
  55509. }
  55510. };
  55511. this._collisionsCallbackArray = [];
  55512. this._init = false;
  55513. this._runningUpdated = 0;
  55514. this._addUpdateMeshesList = {};
  55515. this._addUpdateGeometriesList = {};
  55516. this._toRemoveGeometryArray = [];
  55517. this._toRemoveMeshesArray = [];
  55518. }
  55519. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55520. if (!this._init)
  55521. return;
  55522. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55523. return;
  55524. position.divideToRef(collider._radius, this._scaledPosition);
  55525. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55526. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55527. var payload = {
  55528. collider: {
  55529. position: this._scaledPosition.asArray(),
  55530. velocity: this._scaledVelocity.asArray(),
  55531. radius: collider._radius.asArray()
  55532. },
  55533. collisionId: collisionIndex,
  55534. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55535. maximumRetry: maximumRetry
  55536. };
  55537. var message = {
  55538. payload: payload,
  55539. taskType: WorkerTaskType.COLLIDE
  55540. };
  55541. this._worker.postMessage(message);
  55542. };
  55543. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55544. this._scene = scene;
  55545. this._scene.registerAfterRender(this._afterRender);
  55546. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55547. this._worker = new Worker(workerUrl);
  55548. this._worker.onmessage = this._onMessageFromWorker;
  55549. var message = {
  55550. payload: {},
  55551. taskType: WorkerTaskType.INIT
  55552. };
  55553. this._worker.postMessage(message);
  55554. };
  55555. CollisionCoordinatorWorker.prototype.destroy = function () {
  55556. this._scene.unregisterAfterRender(this._afterRender);
  55557. this._worker.terminate();
  55558. };
  55559. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55560. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55561. this.onMeshUpdated(mesh);
  55562. };
  55563. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55564. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55565. };
  55566. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55567. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55568. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55569. this.onGeometryUpdated(geometry);
  55570. };
  55571. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55572. this._toRemoveGeometryArray.push(geometry.id);
  55573. };
  55574. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55575. var submeshes = [];
  55576. if (mesh.subMeshes) {
  55577. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55578. var boundingInfo = sm.getBoundingInfo();
  55579. return {
  55580. position: idx,
  55581. verticesStart: sm.verticesStart,
  55582. verticesCount: sm.verticesCount,
  55583. indexStart: sm.indexStart,
  55584. indexCount: sm.indexCount,
  55585. hasMaterial: !!sm.getMaterial(),
  55586. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55587. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55588. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55589. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55590. };
  55591. });
  55592. }
  55593. var geometryId = null;
  55594. if (mesh instanceof BABYLON.Mesh) {
  55595. var geometry = mesh.geometry;
  55596. geometryId = geometry ? geometry.id : null;
  55597. }
  55598. else if (mesh instanceof BABYLON.InstancedMesh) {
  55599. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55600. geometryId = geometry ? geometry.id : null;
  55601. }
  55602. var boundingInfo = mesh.getBoundingInfo();
  55603. return {
  55604. uniqueId: mesh.uniqueId,
  55605. id: mesh.id,
  55606. name: mesh.name,
  55607. geometryId: geometryId,
  55608. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55609. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55610. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55611. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55612. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55613. subMeshes: submeshes,
  55614. checkCollisions: mesh.checkCollisions
  55615. };
  55616. };
  55617. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55618. return {
  55619. id: geometry.id,
  55620. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55621. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55622. indices: new Uint32Array(geometry.getIndices() || []),
  55623. };
  55624. };
  55625. return CollisionCoordinatorWorker;
  55626. }());
  55627. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55628. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55629. function CollisionCoordinatorLegacy() {
  55630. this._scaledPosition = BABYLON.Vector3.Zero();
  55631. this._scaledVelocity = BABYLON.Vector3.Zero();
  55632. this._finalPosition = BABYLON.Vector3.Zero();
  55633. }
  55634. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55635. position.divideToRef(collider._radius, this._scaledPosition);
  55636. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55637. collider.collidedMesh = null;
  55638. collider._retry = 0;
  55639. collider._initialVelocity = this._scaledVelocity;
  55640. collider._initialPosition = this._scaledPosition;
  55641. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55642. this._finalPosition.multiplyInPlace(collider._radius);
  55643. //run the callback
  55644. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55645. };
  55646. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55647. this._scene = scene;
  55648. };
  55649. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55650. //Legacy need no destruction method.
  55651. };
  55652. //No update in legacy mode
  55653. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55654. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55655. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55656. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55657. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55658. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55659. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55660. if (excludedMesh === void 0) { excludedMesh = null; }
  55661. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55662. if (collider._retry >= maximumRetry) {
  55663. finalPosition.copyFrom(position);
  55664. return;
  55665. }
  55666. // Check if this is a mesh else camera or -1
  55667. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55668. collider._initialize(position, velocity, closeDistance);
  55669. // Check all meshes
  55670. for (var index = 0; index < this._scene.meshes.length; index++) {
  55671. var mesh = this._scene.meshes[index];
  55672. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55673. mesh._checkCollision(collider);
  55674. }
  55675. }
  55676. if (!collider.collisionFound) {
  55677. position.addToRef(velocity, finalPosition);
  55678. return;
  55679. }
  55680. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55681. collider._getResponse(position, velocity);
  55682. }
  55683. if (velocity.length() <= closeDistance) {
  55684. finalPosition.copyFrom(position);
  55685. return;
  55686. }
  55687. collider._retry++;
  55688. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55689. };
  55690. return CollisionCoordinatorLegacy;
  55691. }());
  55692. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55693. })(BABYLON || (BABYLON = {}));
  55694. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55695. var BABYLON;
  55696. (function (BABYLON) {
  55697. /**
  55698. * A particle represents one of the element emitted by a particle system.
  55699. * This is mainly define by its coordinates, direction, velocity and age.
  55700. */
  55701. var Particle = /** @class */ (function () {
  55702. /**
  55703. * Creates a new instance Particle
  55704. * @param particleSystem the particle system the particle belongs to
  55705. */
  55706. function Particle(
  55707. /**
  55708. * particleSystem the particle system the particle belongs to.
  55709. */
  55710. particleSystem) {
  55711. this.particleSystem = particleSystem;
  55712. /**
  55713. * The world position of the particle in the scene.
  55714. */
  55715. this.position = BABYLON.Vector3.Zero();
  55716. /**
  55717. * The world direction of the particle in the scene.
  55718. */
  55719. this.direction = BABYLON.Vector3.Zero();
  55720. /**
  55721. * The color of the particle.
  55722. */
  55723. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55724. /**
  55725. * The color change of the particle per step.
  55726. */
  55727. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55728. /**
  55729. * Defines how long will the life of the particle be.
  55730. */
  55731. this.lifeTime = 1.0;
  55732. /**
  55733. * The current age of the particle.
  55734. */
  55735. this.age = 0;
  55736. /**
  55737. * The current size of the particle.
  55738. */
  55739. this.size = 0;
  55740. /**
  55741. * The current angle of the particle.
  55742. */
  55743. this.angle = 0;
  55744. /**
  55745. * Defines how fast is the angle changing.
  55746. */
  55747. this.angularSpeed = 0;
  55748. /**
  55749. * Defines the cell index used by the particle to be rendered from a sprite.
  55750. */
  55751. this.cellIndex = 0;
  55752. this._currentFrameCounter = 0;
  55753. if (!this.particleSystem.isAnimationSheetEnabled) {
  55754. return;
  55755. }
  55756. this.updateCellInfoFromSystem();
  55757. }
  55758. Particle.prototype.updateCellInfoFromSystem = function () {
  55759. this.cellIndex = this.particleSystem.startSpriteCellID;
  55760. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55761. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55762. }
  55763. else {
  55764. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55765. }
  55766. };
  55767. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55768. // (ageOffset / scaledUpdateSpeed) / available cells
  55769. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55770. this._currentFrameCounter += scaledUpdateSpeed;
  55771. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55772. this._currentFrameCounter = 0;
  55773. this.cellIndex++;
  55774. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55775. this.cellIndex = this.particleSystem.endSpriteCellID;
  55776. }
  55777. }
  55778. };
  55779. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55780. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55781. this.cellIndex++;
  55782. this._currentFrameCounter = 0;
  55783. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55784. if (this.particleSystem.spriteCellLoop) {
  55785. this.cellIndex = this.particleSystem.startSpriteCellID;
  55786. }
  55787. else {
  55788. this.cellIndex = this.particleSystem.endSpriteCellID;
  55789. }
  55790. }
  55791. }
  55792. else {
  55793. this._currentFrameCounter++;
  55794. }
  55795. };
  55796. /**
  55797. * Copy the properties of particle to another one.
  55798. * @param other the particle to copy the information to.
  55799. */
  55800. Particle.prototype.copyTo = function (other) {
  55801. other.position.copyFrom(this.position);
  55802. other.direction.copyFrom(this.direction);
  55803. other.color.copyFrom(this.color);
  55804. other.colorStep.copyFrom(this.colorStep);
  55805. other.lifeTime = this.lifeTime;
  55806. other.age = this.age;
  55807. other.size = this.size;
  55808. other.angle = this.angle;
  55809. other.angularSpeed = this.angularSpeed;
  55810. other.particleSystem = this.particleSystem;
  55811. other.cellIndex = this.cellIndex;
  55812. };
  55813. return Particle;
  55814. }());
  55815. BABYLON.Particle = Particle;
  55816. })(BABYLON || (BABYLON = {}));
  55817. //# sourceMappingURL=babylon.particle.js.map
  55818. var BABYLON;
  55819. (function (BABYLON) {
  55820. /**
  55821. * This represents a particle system in Babylon.
  55822. * 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.
  55823. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55824. * @example https://doc.babylonjs.com/babylon101/particles
  55825. */
  55826. var ParticleSystem = /** @class */ (function () {
  55827. /**
  55828. * Instantiates a particle system.
  55829. * 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.
  55830. * @param name The name of the particle system
  55831. * @param capacity The max number of particles alive at the same time
  55832. * @param scene The scene the particle system belongs to
  55833. * @param customEffect a custom effect used to change the way particles are rendered by default
  55834. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55835. * @param epsilon Offset used to render the particles
  55836. */
  55837. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55838. if (customEffect === void 0) { customEffect = null; }
  55839. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55840. if (epsilon === void 0) { epsilon = 0.01; }
  55841. var _this = this;
  55842. /**
  55843. * List of animations used by the particle system.
  55844. */
  55845. this.animations = [];
  55846. /**
  55847. * The rendering group used by the Particle system to chose when to render.
  55848. */
  55849. this.renderingGroupId = 0;
  55850. /**
  55851. * The emitter represents the Mesh or position we are attaching the particle system to.
  55852. */
  55853. this.emitter = null;
  55854. /**
  55855. * The maximum number of particles to emit per frame
  55856. */
  55857. this.emitRate = 10;
  55858. /**
  55859. * If you want to launch only a few particles at once, that can be done, as well.
  55860. */
  55861. this.manualEmitCount = -1;
  55862. /**
  55863. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55864. */
  55865. this.updateSpeed = 0.01;
  55866. /**
  55867. * The amount of time the particle system is running (depends of the overall update speed).
  55868. */
  55869. this.targetStopDuration = 0;
  55870. /**
  55871. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55872. */
  55873. this.disposeOnStop = false;
  55874. /**
  55875. * Minimum power of emitting particles.
  55876. */
  55877. this.minEmitPower = 1;
  55878. /**
  55879. * Maximum power of emitting particles.
  55880. */
  55881. this.maxEmitPower = 1;
  55882. /**
  55883. * Minimum life time of emitting particles.
  55884. */
  55885. this.minLifeTime = 1;
  55886. /**
  55887. * Maximum life time of emitting particles.
  55888. */
  55889. this.maxLifeTime = 1;
  55890. /**
  55891. * Minimum Size of emitting particles.
  55892. */
  55893. this.minSize = 1;
  55894. /**
  55895. * Maximum Size of emitting particles.
  55896. */
  55897. this.maxSize = 1;
  55898. /**
  55899. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55900. */
  55901. this.minAngularSpeed = 0;
  55902. /**
  55903. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55904. */
  55905. this.maxAngularSpeed = 0;
  55906. /**
  55907. * The layer mask we are rendering the particles through.
  55908. */
  55909. this.layerMask = 0x0FFFFFFF;
  55910. /**
  55911. * This can help using your own shader to render the particle system.
  55912. * The according effect will be created
  55913. */
  55914. this.customShader = null;
  55915. /**
  55916. * By default particle system starts as soon as they are created. This prevents the
  55917. * automatic start to happen and let you decide when to start emitting particles.
  55918. */
  55919. this.preventAutoStart = false;
  55920. /**
  55921. * Callback triggered when the particle animation is ending.
  55922. */
  55923. this.onAnimationEnd = null;
  55924. /**
  55925. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55926. */
  55927. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55928. /**
  55929. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55930. * to override the particles.
  55931. */
  55932. this.forceDepthWrite = false;
  55933. /**
  55934. * You can use gravity if you want to give an orientation to your particles.
  55935. */
  55936. this.gravity = BABYLON.Vector3.Zero();
  55937. /**
  55938. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55939. */
  55940. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55941. /**
  55942. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55943. */
  55944. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55945. /**
  55946. * Color the particle will have at the end of its lifetime.
  55947. */
  55948. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55949. /**
  55950. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55951. */
  55952. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55953. /**
  55954. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55955. */
  55956. this.spriteCellLoop = true;
  55957. /**
  55958. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55959. */
  55960. this.spriteCellChangeSpeed = 0;
  55961. /**
  55962. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55963. */
  55964. this.startSpriteCellID = 0;
  55965. /**
  55966. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55967. */
  55968. this.endSpriteCellID = 0;
  55969. /**
  55970. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55971. */
  55972. this.spriteCellWidth = 0;
  55973. /**
  55974. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55975. */
  55976. this.spriteCellHeight = 0;
  55977. /**
  55978. * An event triggered when the system is disposed.
  55979. */
  55980. this.onDisposeObservable = new BABYLON.Observable();
  55981. this._particles = new Array();
  55982. this._stockParticles = new Array();
  55983. this._newPartsExcess = 0;
  55984. this._vertexBuffers = {};
  55985. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55986. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55987. this._scaledDirection = BABYLON.Vector3.Zero();
  55988. this._scaledGravity = BABYLON.Vector3.Zero();
  55989. this._currentRenderId = -1;
  55990. this._started = false;
  55991. this._stopped = false;
  55992. this._actualFrame = 0;
  55993. this._vertexBufferSize = 11;
  55994. // start of sub system methods
  55995. /**
  55996. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55997. * Its lifetime will start back at 0.
  55998. */
  55999. this.recycleParticle = function (particle) {
  56000. var lastParticle = _this._particles.pop();
  56001. if (lastParticle !== particle) {
  56002. lastParticle.copyTo(particle);
  56003. }
  56004. _this._stockParticles.push(lastParticle);
  56005. };
  56006. this._createParticle = function () {
  56007. var particle;
  56008. if (_this._stockParticles.length !== 0) {
  56009. particle = _this._stockParticles.pop();
  56010. particle.age = 0;
  56011. particle.cellIndex = _this.startSpriteCellID;
  56012. }
  56013. else {
  56014. particle = new BABYLON.Particle(_this);
  56015. }
  56016. return particle;
  56017. };
  56018. this._emitFromParticle = function (particle) {
  56019. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56020. return;
  56021. }
  56022. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56023. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56024. subSystem._rootParticleSystem = _this;
  56025. _this.activeSubSystems.push(subSystem);
  56026. subSystem.start();
  56027. };
  56028. this._appendParticleVertexes = null;
  56029. this.id = name;
  56030. this.name = name;
  56031. this._capacity = capacity;
  56032. this._epsilon = epsilon;
  56033. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56034. if (isAnimationSheetEnabled) {
  56035. this._vertexBufferSize = 12;
  56036. }
  56037. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56038. this._customEffect = customEffect;
  56039. scene.particleSystems.push(this);
  56040. this._createIndexBuffer();
  56041. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56042. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56043. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56044. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56045. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56046. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56047. if (this._isAnimationSheetEnabled) {
  56048. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56049. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56050. }
  56051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56052. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56053. this._vertexBuffers["options"] = options;
  56054. // Default emitter type
  56055. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56056. this.updateFunction = function (particles) {
  56057. for (var index = 0; index < particles.length; index++) {
  56058. var particle = particles[index];
  56059. particle.age += _this._scaledUpdateSpeed;
  56060. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56061. _this._emitFromParticle(particle);
  56062. _this.recycleParticle(particle);
  56063. index--;
  56064. continue;
  56065. }
  56066. else {
  56067. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56068. particle.color.addInPlace(_this._scaledColorStep);
  56069. if (particle.color.a < 0)
  56070. particle.color.a = 0;
  56071. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56072. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56073. particle.position.addInPlace(_this._scaledDirection);
  56074. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56075. particle.direction.addInPlace(_this._scaledGravity);
  56076. if (_this._isAnimationSheetEnabled) {
  56077. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56078. }
  56079. }
  56080. }
  56081. };
  56082. }
  56083. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56084. /**
  56085. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56086. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56087. */
  56088. get: function () {
  56089. if (this.particleEmitterType.direction1) {
  56090. return this.particleEmitterType.direction1;
  56091. }
  56092. return BABYLON.Vector3.Zero();
  56093. },
  56094. set: function (value) {
  56095. if (this.particleEmitterType.direction1) {
  56096. this.particleEmitterType.direction1 = value;
  56097. }
  56098. },
  56099. enumerable: true,
  56100. configurable: true
  56101. });
  56102. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56103. /**
  56104. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56105. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56106. */
  56107. get: function () {
  56108. if (this.particleEmitterType.direction2) {
  56109. return this.particleEmitterType.direction2;
  56110. }
  56111. return BABYLON.Vector3.Zero();
  56112. },
  56113. set: function (value) {
  56114. if (this.particleEmitterType.direction2) {
  56115. this.particleEmitterType.direction2 = value;
  56116. }
  56117. },
  56118. enumerable: true,
  56119. configurable: true
  56120. });
  56121. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56122. /**
  56123. * 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.
  56124. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56125. */
  56126. get: function () {
  56127. if (this.particleEmitterType.minEmitBox) {
  56128. return this.particleEmitterType.minEmitBox;
  56129. }
  56130. return BABYLON.Vector3.Zero();
  56131. },
  56132. set: function (value) {
  56133. if (this.particleEmitterType.minEmitBox) {
  56134. this.particleEmitterType.minEmitBox = value;
  56135. }
  56136. },
  56137. enumerable: true,
  56138. configurable: true
  56139. });
  56140. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56141. /**
  56142. * 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.
  56143. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56144. */
  56145. get: function () {
  56146. if (this.particleEmitterType.maxEmitBox) {
  56147. return this.particleEmitterType.maxEmitBox;
  56148. }
  56149. return BABYLON.Vector3.Zero();
  56150. },
  56151. set: function (value) {
  56152. if (this.particleEmitterType.maxEmitBox) {
  56153. this.particleEmitterType.maxEmitBox = value;
  56154. }
  56155. },
  56156. enumerable: true,
  56157. configurable: true
  56158. });
  56159. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56160. /**
  56161. * Sets a callback that will be triggered when the system is disposed.
  56162. */
  56163. set: function (callback) {
  56164. if (this._onDisposeObserver) {
  56165. this.onDisposeObservable.remove(this._onDisposeObserver);
  56166. }
  56167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56168. },
  56169. enumerable: true,
  56170. configurable: true
  56171. });
  56172. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56173. /**
  56174. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56175. */
  56176. get: function () {
  56177. return this._isAnimationSheetEnabled;
  56178. },
  56179. enumerable: true,
  56180. configurable: true
  56181. });
  56182. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56183. //end of Sub-emitter
  56184. /**
  56185. * Gets the current list of active particles
  56186. */
  56187. get: function () {
  56188. return this._particles;
  56189. },
  56190. enumerable: true,
  56191. configurable: true
  56192. });
  56193. /**
  56194. * Returns the string "ParticleSystem"
  56195. * @returns a string containing the class name
  56196. */
  56197. ParticleSystem.prototype.getClassName = function () {
  56198. return "ParticleSystem";
  56199. };
  56200. ParticleSystem.prototype._createIndexBuffer = function () {
  56201. var indices = [];
  56202. var index = 0;
  56203. for (var count = 0; count < this._capacity; count++) {
  56204. indices.push(index);
  56205. indices.push(index + 1);
  56206. indices.push(index + 2);
  56207. indices.push(index);
  56208. indices.push(index + 2);
  56209. indices.push(index + 3);
  56210. index += 4;
  56211. }
  56212. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56213. };
  56214. /**
  56215. * Gets the maximum number of particles active at the same time.
  56216. * @returns The max number of active particles.
  56217. */
  56218. ParticleSystem.prototype.getCapacity = function () {
  56219. return this._capacity;
  56220. };
  56221. /**
  56222. * Gets Wether there are still active particles in the system.
  56223. * @returns True if it is alive, otherwise false.
  56224. */
  56225. ParticleSystem.prototype.isAlive = function () {
  56226. return this._alive;
  56227. };
  56228. /**
  56229. * Gets Wether the system has been started.
  56230. * @returns True if it has been started, otherwise false.
  56231. */
  56232. ParticleSystem.prototype.isStarted = function () {
  56233. return this._started;
  56234. };
  56235. /**
  56236. * Starts the particle system and begins to emit.
  56237. */
  56238. ParticleSystem.prototype.start = function () {
  56239. this._started = true;
  56240. this._stopped = false;
  56241. this._actualFrame = 0;
  56242. if (this.subEmitters && this.subEmitters.length != 0) {
  56243. this.activeSubSystems = new Array();
  56244. }
  56245. };
  56246. /**
  56247. * Stops the particle system.
  56248. * @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.
  56249. */
  56250. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56251. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56252. this._stopped = true;
  56253. if (stopSubEmitters) {
  56254. this._stopSubEmitters();
  56255. }
  56256. };
  56257. // animation sheet
  56258. /**
  56259. * Remove all active particles
  56260. */
  56261. ParticleSystem.prototype.reset = function () {
  56262. this._stockParticles = [];
  56263. this._particles = [];
  56264. };
  56265. /**
  56266. * @hidden (for internal use only)
  56267. */
  56268. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56269. var offset = index * this._vertexBufferSize;
  56270. this._vertexData[offset] = particle.position.x;
  56271. this._vertexData[offset + 1] = particle.position.y;
  56272. this._vertexData[offset + 2] = particle.position.z;
  56273. this._vertexData[offset + 3] = particle.color.r;
  56274. this._vertexData[offset + 4] = particle.color.g;
  56275. this._vertexData[offset + 5] = particle.color.b;
  56276. this._vertexData[offset + 6] = particle.color.a;
  56277. this._vertexData[offset + 7] = particle.angle;
  56278. this._vertexData[offset + 8] = particle.size;
  56279. this._vertexData[offset + 9] = offsetX;
  56280. this._vertexData[offset + 10] = offsetY;
  56281. };
  56282. /**
  56283. * @hidden (for internal use only)
  56284. */
  56285. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56286. if (offsetX === 0)
  56287. offsetX = this._epsilon;
  56288. else if (offsetX === 1)
  56289. offsetX = 1 - this._epsilon;
  56290. if (offsetY === 0)
  56291. offsetY = this._epsilon;
  56292. else if (offsetY === 1)
  56293. offsetY = 1 - this._epsilon;
  56294. var offset = index * this._vertexBufferSize;
  56295. this._vertexData[offset] = particle.position.x;
  56296. this._vertexData[offset + 1] = particle.position.y;
  56297. this._vertexData[offset + 2] = particle.position.z;
  56298. this._vertexData[offset + 3] = particle.color.r;
  56299. this._vertexData[offset + 4] = particle.color.g;
  56300. this._vertexData[offset + 5] = particle.color.b;
  56301. this._vertexData[offset + 6] = particle.color.a;
  56302. this._vertexData[offset + 7] = particle.angle;
  56303. this._vertexData[offset + 8] = particle.size;
  56304. this._vertexData[offset + 9] = offsetX;
  56305. this._vertexData[offset + 10] = offsetY;
  56306. this._vertexData[offset + 11] = particle.cellIndex;
  56307. };
  56308. ParticleSystem.prototype._stopSubEmitters = function () {
  56309. if (!this.activeSubSystems) {
  56310. return;
  56311. }
  56312. this.activeSubSystems.forEach(function (subSystem) {
  56313. subSystem.stop(true);
  56314. });
  56315. this.activeSubSystems = new Array();
  56316. };
  56317. ParticleSystem.prototype._removeFromRoot = function () {
  56318. if (!this._rootParticleSystem) {
  56319. return;
  56320. }
  56321. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56322. if (index !== -1) {
  56323. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56324. }
  56325. };
  56326. // end of sub system methods
  56327. ParticleSystem.prototype._update = function (newParticles) {
  56328. // Update current
  56329. this._alive = this._particles.length > 0;
  56330. this.updateFunction(this._particles);
  56331. // Add new ones
  56332. var worldMatrix;
  56333. if (this.emitter.position) {
  56334. var emitterMesh = this.emitter;
  56335. worldMatrix = emitterMesh.getWorldMatrix();
  56336. }
  56337. else {
  56338. var emitterPosition = this.emitter;
  56339. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56340. }
  56341. var particle;
  56342. for (var index = 0; index < newParticles; index++) {
  56343. if (this._particles.length === this._capacity) {
  56344. break;
  56345. }
  56346. particle = this._createParticle();
  56347. this._particles.push(particle);
  56348. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56349. if (this.startPositionFunction) {
  56350. this.startPositionFunction(worldMatrix, particle.position, particle);
  56351. }
  56352. else {
  56353. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56354. }
  56355. if (this.startDirectionFunction) {
  56356. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56357. }
  56358. else {
  56359. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56360. }
  56361. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56362. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56363. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56364. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56365. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56366. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56367. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56368. }
  56369. };
  56370. ParticleSystem.prototype._getEffect = function () {
  56371. if (this._customEffect) {
  56372. return this._customEffect;
  56373. }
  56374. ;
  56375. var defines = [];
  56376. if (this._scene.clipPlane) {
  56377. defines.push("#define CLIPPLANE");
  56378. }
  56379. if (this._isAnimationSheetEnabled) {
  56380. defines.push("#define ANIMATESHEET");
  56381. }
  56382. // Effect
  56383. var join = defines.join("\n");
  56384. if (this._cachedDefines !== join) {
  56385. this._cachedDefines = join;
  56386. var attributesNamesOrOptions;
  56387. var effectCreationOption;
  56388. if (this._isAnimationSheetEnabled) {
  56389. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56390. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56391. }
  56392. else {
  56393. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56394. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56395. }
  56396. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56397. }
  56398. return this._effect;
  56399. };
  56400. /**
  56401. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56402. */
  56403. ParticleSystem.prototype.animate = function () {
  56404. if (!this._started)
  56405. return;
  56406. var effect = this._getEffect();
  56407. // Check
  56408. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56409. return;
  56410. if (this._currentRenderId === this._scene.getRenderId()) {
  56411. return;
  56412. }
  56413. this._currentRenderId = this._scene.getRenderId();
  56414. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56415. // determine the number of particles we need to create
  56416. var newParticles;
  56417. if (this.manualEmitCount > -1) {
  56418. newParticles = this.manualEmitCount;
  56419. this._newPartsExcess = 0;
  56420. this.manualEmitCount = 0;
  56421. }
  56422. else {
  56423. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56424. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56425. }
  56426. if (this._newPartsExcess > 1.0) {
  56427. newParticles += this._newPartsExcess >> 0;
  56428. this._newPartsExcess -= this._newPartsExcess >> 0;
  56429. }
  56430. this._alive = false;
  56431. if (!this._stopped) {
  56432. this._actualFrame += this._scaledUpdateSpeed;
  56433. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56434. this.stop();
  56435. }
  56436. else {
  56437. newParticles = 0;
  56438. }
  56439. this._update(newParticles);
  56440. // Stopped?
  56441. if (this._stopped) {
  56442. if (!this._alive) {
  56443. this._started = false;
  56444. if (this.onAnimationEnd) {
  56445. this.onAnimationEnd();
  56446. }
  56447. if (this.disposeOnStop) {
  56448. this._scene._toBeDisposed.push(this);
  56449. }
  56450. }
  56451. }
  56452. // Animation sheet
  56453. if (this._isAnimationSheetEnabled) {
  56454. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56455. }
  56456. else {
  56457. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56458. }
  56459. // Update VBO
  56460. var offset = 0;
  56461. for (var index = 0; index < this._particles.length; index++) {
  56462. var particle = this._particles[index];
  56463. this._appendParticleVertexes(offset, particle);
  56464. offset += 4;
  56465. }
  56466. if (this._vertexBuffer) {
  56467. this._vertexBuffer.update(this._vertexData);
  56468. }
  56469. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56470. this.stop();
  56471. }
  56472. };
  56473. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56474. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56475. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56476. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56477. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56478. };
  56479. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56480. this._appendParticleVertex(offset++, particle, 0, 0);
  56481. this._appendParticleVertex(offset++, particle, 1, 0);
  56482. this._appendParticleVertex(offset++, particle, 1, 1);
  56483. this._appendParticleVertex(offset++, particle, 0, 1);
  56484. };
  56485. /**
  56486. * Rebuilds the particle system.
  56487. */
  56488. ParticleSystem.prototype.rebuild = function () {
  56489. this._createIndexBuffer();
  56490. if (this._vertexBuffer) {
  56491. this._vertexBuffer._rebuild();
  56492. }
  56493. };
  56494. /**
  56495. * Is this system ready to be used/rendered
  56496. * @return true if the system is ready
  56497. */
  56498. ParticleSystem.prototype.isReady = function () {
  56499. var effect = this._getEffect();
  56500. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56501. return false;
  56502. }
  56503. return true;
  56504. };
  56505. /**
  56506. * Renders the particle system in its current state.
  56507. * @returns the current number of particles
  56508. */
  56509. ParticleSystem.prototype.render = function () {
  56510. var effect = this._getEffect();
  56511. // Check
  56512. if (!this.isReady() || !this._particles.length) {
  56513. return 0;
  56514. }
  56515. var engine = this._scene.getEngine();
  56516. // Render
  56517. engine.enableEffect(effect);
  56518. engine.setState(false);
  56519. var viewMatrix = this._scene.getViewMatrix();
  56520. effect.setTexture("diffuseSampler", this.particleTexture);
  56521. effect.setMatrix("view", viewMatrix);
  56522. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56523. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56524. var baseSize = this.particleTexture.getBaseSize();
  56525. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56526. }
  56527. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56528. if (this._scene.clipPlane) {
  56529. var clipPlane = this._scene.clipPlane;
  56530. var invView = viewMatrix.clone();
  56531. invView.invert();
  56532. effect.setMatrix("invView", invView);
  56533. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56534. }
  56535. // VBOs
  56536. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56537. // Draw order
  56538. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56539. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56540. }
  56541. else {
  56542. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56543. }
  56544. if (this.forceDepthWrite) {
  56545. engine.setDepthWrite(true);
  56546. }
  56547. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56548. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56549. return this._particles.length;
  56550. };
  56551. /**
  56552. * Disposes the particle system and free the associated resources
  56553. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56554. */
  56555. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56556. if (disposeTexture === void 0) { disposeTexture = true; }
  56557. if (this._vertexBuffer) {
  56558. this._vertexBuffer.dispose();
  56559. this._vertexBuffer = null;
  56560. }
  56561. if (this._indexBuffer) {
  56562. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56563. this._indexBuffer = null;
  56564. }
  56565. if (disposeTexture && this.particleTexture) {
  56566. this.particleTexture.dispose();
  56567. this.particleTexture = null;
  56568. }
  56569. this._removeFromRoot();
  56570. // Remove from scene
  56571. var index = this._scene.particleSystems.indexOf(this);
  56572. if (index > -1) {
  56573. this._scene.particleSystems.splice(index, 1);
  56574. }
  56575. // Callback
  56576. this.onDisposeObservable.notifyObservers(this);
  56577. this.onDisposeObservable.clear();
  56578. };
  56579. /**
  56580. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56581. * @param radius The radius of the sphere to emit from
  56582. * @returns the emitter
  56583. */
  56584. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56585. if (radius === void 0) { radius = 1; }
  56586. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56587. this.particleEmitterType = particleEmitter;
  56588. return particleEmitter;
  56589. };
  56590. /**
  56591. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56592. * @param radius The radius of the sphere to emit from
  56593. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56594. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56595. * @returns the emitter
  56596. */
  56597. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56598. if (radius === void 0) { radius = 1; }
  56599. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56600. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56601. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56602. this.particleEmitterType = particleEmitter;
  56603. return particleEmitter;
  56604. };
  56605. /**
  56606. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56607. * @param radius The radius of the cone to emit from
  56608. * @param angle The base angle of the cone
  56609. * @returns the emitter
  56610. */
  56611. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56612. if (radius === void 0) { radius = 1; }
  56613. if (angle === void 0) { angle = Math.PI / 4; }
  56614. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56615. this.particleEmitterType = particleEmitter;
  56616. return particleEmitter;
  56617. };
  56618. // 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.
  56619. /**
  56620. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56621. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56622. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56623. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56624. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56625. * @returns the emitter
  56626. */
  56627. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56628. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56629. this.particleEmitterType = particleEmitter;
  56630. this.direction1 = direction1;
  56631. this.direction2 = direction2;
  56632. this.minEmitBox = minEmitBox;
  56633. this.maxEmitBox = maxEmitBox;
  56634. return particleEmitter;
  56635. };
  56636. // Clone
  56637. /**
  56638. * Clones the particle system.
  56639. * @param name The name of the cloned object
  56640. * @param newEmitter The new emitter to use
  56641. * @returns the cloned particle system
  56642. */
  56643. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56644. var custom = null;
  56645. var program = null;
  56646. if (this.customShader != null) {
  56647. program = this.customShader;
  56648. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56649. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56650. }
  56651. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56652. result.customShader = program;
  56653. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56654. if (newEmitter === undefined) {
  56655. newEmitter = this.emitter;
  56656. }
  56657. result.emitter = newEmitter;
  56658. if (this.particleTexture) {
  56659. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56660. }
  56661. if (!this.preventAutoStart) {
  56662. result.start();
  56663. }
  56664. return result;
  56665. };
  56666. /**
  56667. * Serializes the particle system to a JSON object.
  56668. * @returns the JSON object
  56669. */
  56670. ParticleSystem.prototype.serialize = function () {
  56671. var serializationObject = {};
  56672. serializationObject.name = this.name;
  56673. serializationObject.id = this.id;
  56674. // Emitter
  56675. if (this.emitter.position) {
  56676. var emitterMesh = this.emitter;
  56677. serializationObject.emitterId = emitterMesh.id;
  56678. }
  56679. else {
  56680. var emitterPosition = this.emitter;
  56681. serializationObject.emitter = emitterPosition.asArray();
  56682. }
  56683. serializationObject.capacity = this.getCapacity();
  56684. if (this.particleTexture) {
  56685. serializationObject.textureName = this.particleTexture.name;
  56686. }
  56687. // Animations
  56688. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56689. // Particle system
  56690. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56691. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56692. serializationObject.minSize = this.minSize;
  56693. serializationObject.maxSize = this.maxSize;
  56694. serializationObject.minEmitPower = this.minEmitPower;
  56695. serializationObject.maxEmitPower = this.maxEmitPower;
  56696. serializationObject.minLifeTime = this.minLifeTime;
  56697. serializationObject.maxLifeTime = this.maxLifeTime;
  56698. serializationObject.emitRate = this.emitRate;
  56699. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56700. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56701. serializationObject.gravity = this.gravity.asArray();
  56702. serializationObject.direction1 = this.direction1.asArray();
  56703. serializationObject.direction2 = this.direction2.asArray();
  56704. serializationObject.color1 = this.color1.asArray();
  56705. serializationObject.color2 = this.color2.asArray();
  56706. serializationObject.colorDead = this.colorDead.asArray();
  56707. serializationObject.updateSpeed = this.updateSpeed;
  56708. serializationObject.targetStopDuration = this.targetStopDuration;
  56709. serializationObject.textureMask = this.textureMask.asArray();
  56710. serializationObject.blendMode = this.blendMode;
  56711. serializationObject.customShader = this.customShader;
  56712. serializationObject.preventAutoStart = this.preventAutoStart;
  56713. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56714. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56715. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56716. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56717. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56718. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56719. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56720. // Emitter
  56721. if (this.particleEmitterType) {
  56722. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56723. }
  56724. return serializationObject;
  56725. };
  56726. /**
  56727. * Parses a JSON object to create a particle system.
  56728. * @param parsedParticleSystem The JSON object to parse
  56729. * @param scene The scene to create the particle system in
  56730. * @param rootUrl The root url to use to load external dependencies like texture
  56731. * @returns the Parsed particle system
  56732. */
  56733. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56734. var name = parsedParticleSystem.name;
  56735. var custom = null;
  56736. var program = null;
  56737. if (parsedParticleSystem.customShader) {
  56738. program = parsedParticleSystem.customShader;
  56739. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56740. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56741. }
  56742. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56743. particleSystem.customShader = program;
  56744. if (parsedParticleSystem.id) {
  56745. particleSystem.id = parsedParticleSystem.id;
  56746. }
  56747. // Auto start
  56748. if (parsedParticleSystem.preventAutoStart) {
  56749. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56750. }
  56751. // Texture
  56752. if (parsedParticleSystem.textureName) {
  56753. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56754. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56755. }
  56756. // Emitter
  56757. if (parsedParticleSystem.emitterId) {
  56758. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56759. }
  56760. else {
  56761. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56762. }
  56763. // Animations
  56764. if (parsedParticleSystem.animations) {
  56765. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56766. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56767. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56768. }
  56769. }
  56770. if (parsedParticleSystem.autoAnimate) {
  56771. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56772. }
  56773. // Particle system
  56774. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56775. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56776. particleSystem.minSize = parsedParticleSystem.minSize;
  56777. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56778. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56779. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56780. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56781. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56782. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56783. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56784. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56785. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56786. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56787. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56788. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56789. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56790. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56791. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56792. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56793. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56794. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56795. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56796. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56797. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56798. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56799. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56800. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56801. if (!particleSystem.preventAutoStart) {
  56802. particleSystem.start();
  56803. }
  56804. return particleSystem;
  56805. };
  56806. /**
  56807. * Source color is added to the destination color without alpha affecting the result.
  56808. */
  56809. ParticleSystem.BLENDMODE_ONEONE = 0;
  56810. /**
  56811. * Blend current color and particle color using particle’s alpha.
  56812. */
  56813. ParticleSystem.BLENDMODE_STANDARD = 1;
  56814. return ParticleSystem;
  56815. }());
  56816. BABYLON.ParticleSystem = ParticleSystem;
  56817. })(BABYLON || (BABYLON = {}));
  56818. //# sourceMappingURL=babylon.particleSystem.js.map
  56819. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56820. var BABYLON;
  56821. (function (BABYLON) {
  56822. /**
  56823. * Particle emitter emitting particles from the inside of a box.
  56824. * It emits the particles randomly between 2 given directions.
  56825. */
  56826. var BoxParticleEmitter = /** @class */ (function () {
  56827. /**
  56828. * Creates a new instance BoxParticleEmitter
  56829. */
  56830. function BoxParticleEmitter() {
  56831. /**
  56832. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56833. */
  56834. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56835. /**
  56836. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56837. */
  56838. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56839. /**
  56840. * 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.
  56841. */
  56842. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56843. /**
  56844. * 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.
  56845. */
  56846. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56847. }
  56848. /**
  56849. * Called by the particle System when the direction is computed for the created particle.
  56850. * @param emitPower is the power of the particle (speed)
  56851. * @param worldMatrix is the world matrix of the particle system
  56852. * @param directionToUpdate is the direction vector to update with the result
  56853. * @param particle is the particle we are computed the direction for
  56854. */
  56855. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56856. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56857. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56858. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56859. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56860. };
  56861. /**
  56862. * Called by the particle System when the position is computed for the created particle.
  56863. * @param worldMatrix is the world matrix of the particle system
  56864. * @param positionToUpdate is the position vector to update with the result
  56865. * @param particle is the particle we are computed the position for
  56866. */
  56867. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56868. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56869. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56870. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56872. };
  56873. /**
  56874. * Clones the current emitter and returns a copy of it
  56875. * @returns the new emitter
  56876. */
  56877. BoxParticleEmitter.prototype.clone = function () {
  56878. var newOne = new BoxParticleEmitter();
  56879. BABYLON.Tools.DeepCopy(this, newOne);
  56880. return newOne;
  56881. };
  56882. /**
  56883. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56884. * @param effect defines the update shader
  56885. */
  56886. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56887. effect.setVector3("direction1", this.direction1);
  56888. effect.setVector3("direction2", this.direction2);
  56889. effect.setVector3("minEmitBox", this.minEmitBox);
  56890. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56891. };
  56892. /**
  56893. * Returns a string to use to update the GPU particles update shader
  56894. * @returns a string containng the defines string
  56895. */
  56896. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56897. return "#define BOXEMITTER";
  56898. };
  56899. /**
  56900. * Returns the string "BoxEmitter"
  56901. * @returns a string containing the class name
  56902. */
  56903. BoxParticleEmitter.prototype.getClassName = function () {
  56904. return "BoxEmitter";
  56905. };
  56906. /**
  56907. * Serializes the particle system to a JSON object.
  56908. * @returns the JSON object
  56909. */
  56910. BoxParticleEmitter.prototype.serialize = function () {
  56911. var serializationObject = {};
  56912. serializationObject.type = this.getClassName();
  56913. serializationObject.direction1 = this.direction1.asArray();
  56914. serializationObject.direction2 = this.direction2.asArray();
  56915. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56916. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56917. return serializationObject;
  56918. };
  56919. /**
  56920. * Parse properties from a JSON object
  56921. * @param serializationObject defines the JSON object
  56922. */
  56923. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56924. this.direction1.copyFrom(serializationObject.direction1);
  56925. this.direction2.copyFrom(serializationObject.direction2);
  56926. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56927. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56928. };
  56929. return BoxParticleEmitter;
  56930. }());
  56931. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56932. })(BABYLON || (BABYLON = {}));
  56933. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56934. var BABYLON;
  56935. (function (BABYLON) {
  56936. /**
  56937. * Particle emitter emitting particles from the inside of a cone.
  56938. * It emits the particles alongside the cone volume from the base to the particle.
  56939. * The emission direction might be randomized.
  56940. */
  56941. var ConeParticleEmitter = /** @class */ (function () {
  56942. /**
  56943. * Creates a new instance ConeParticleEmitter
  56944. * @param radius the radius of the emission cone (1 by default)
  56945. * @param angles the cone base angle (PI by default)
  56946. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56947. */
  56948. function ConeParticleEmitter(radius,
  56949. /**
  56950. * The radius of the emission cone.
  56951. */
  56952. angle,
  56953. /**
  56954. * The cone base angle.
  56955. */
  56956. directionRandomizer) {
  56957. if (radius === void 0) { radius = 1; }
  56958. if (angle === void 0) { angle = Math.PI; }
  56959. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56960. this.angle = angle;
  56961. this.directionRandomizer = directionRandomizer;
  56962. this.radius = radius;
  56963. }
  56964. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56965. /**
  56966. * Gets the radius of the emission cone.
  56967. */
  56968. get: function () {
  56969. return this._radius;
  56970. },
  56971. /**
  56972. * Sets the radius of the emission cone.
  56973. */
  56974. set: function (value) {
  56975. this._radius = value;
  56976. if (this.angle !== 0) {
  56977. this._height = value / Math.tan(this.angle / 2);
  56978. }
  56979. else {
  56980. this._height = 1;
  56981. }
  56982. },
  56983. enumerable: true,
  56984. configurable: true
  56985. });
  56986. /**
  56987. * Called by the particle System when the direction is computed for the created particle.
  56988. * @param emitPower is the power of the particle (speed)
  56989. * @param worldMatrix is the world matrix of the particle system
  56990. * @param directionToUpdate is the direction vector to update with the result
  56991. * @param particle is the particle we are computed the direction for
  56992. */
  56993. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56994. if (this.angle === 0) {
  56995. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56996. }
  56997. else {
  56998. // measure the direction Vector from the emitter to the particle.
  56999. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57000. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57001. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57002. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57003. direction.x += randX;
  57004. direction.y += randY;
  57005. direction.z += randZ;
  57006. direction.normalize();
  57007. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57008. }
  57009. };
  57010. /**
  57011. * Called by the particle System when the position is computed for the created particle.
  57012. * @param worldMatrix is the world matrix of the particle system
  57013. * @param positionToUpdate is the position vector to update with the result
  57014. * @param particle is the particle we are computed the position for
  57015. */
  57016. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57017. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57018. var h = BABYLON.Scalar.RandomRange(0, 1);
  57019. // Better distribution in a cone at normal angles.
  57020. h = 1 - h * h;
  57021. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57022. radius = radius * h;
  57023. var randX = radius * Math.sin(s);
  57024. var randZ = radius * Math.cos(s);
  57025. var randY = h * this._height;
  57026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57027. };
  57028. /**
  57029. * Clones the current emitter and returns a copy of it
  57030. * @returns the new emitter
  57031. */
  57032. ConeParticleEmitter.prototype.clone = function () {
  57033. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57034. BABYLON.Tools.DeepCopy(this, newOne);
  57035. return newOne;
  57036. };
  57037. /**
  57038. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57039. * @param effect defines the update shader
  57040. */
  57041. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57042. effect.setFloat("radius", this.radius);
  57043. effect.setFloat("angle", this.angle);
  57044. effect.setFloat("height", this._height);
  57045. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57046. };
  57047. /**
  57048. * Returns a string to use to update the GPU particles update shader
  57049. * @returns a string containng the defines string
  57050. */
  57051. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57052. return "#define CONEEMITTER";
  57053. };
  57054. /**
  57055. * Returns the string "BoxEmitter"
  57056. * @returns a string containing the class name
  57057. */
  57058. ConeParticleEmitter.prototype.getClassName = function () {
  57059. return "ConeEmitter";
  57060. };
  57061. /**
  57062. * Serializes the particle system to a JSON object.
  57063. * @returns the JSON object
  57064. */
  57065. ConeParticleEmitter.prototype.serialize = function () {
  57066. var serializationObject = {};
  57067. serializationObject.type = this.getClassName();
  57068. serializationObject.radius = this.radius;
  57069. serializationObject.angle = this.angle;
  57070. serializationObject.directionRandomizer = this.directionRandomizer;
  57071. return serializationObject;
  57072. };
  57073. /**
  57074. * Parse properties from a JSON object
  57075. * @param serializationObject defines the JSON object
  57076. */
  57077. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57078. this.radius = serializationObject.radius;
  57079. this.angle = serializationObject.angle;
  57080. this.directionRandomizer = serializationObject.directionRandomizer;
  57081. };
  57082. return ConeParticleEmitter;
  57083. }());
  57084. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57085. })(BABYLON || (BABYLON = {}));
  57086. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57087. var BABYLON;
  57088. (function (BABYLON) {
  57089. /**
  57090. * Particle emitter emitting particles from the inside of a sphere.
  57091. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57092. */
  57093. var SphereParticleEmitter = /** @class */ (function () {
  57094. /**
  57095. * Creates a new instance SphereParticleEmitter
  57096. * @param radius the radius of the emission sphere (1 by default)
  57097. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57098. */
  57099. function SphereParticleEmitter(
  57100. /**
  57101. * The radius of the emission sphere.
  57102. */
  57103. radius,
  57104. /**
  57105. * How much to randomize the particle direction [0-1].
  57106. */
  57107. directionRandomizer) {
  57108. if (radius === void 0) { radius = 1; }
  57109. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57110. this.radius = radius;
  57111. this.directionRandomizer = directionRandomizer;
  57112. }
  57113. /**
  57114. * Called by the particle System when the direction is computed for the created particle.
  57115. * @param emitPower is the power of the particle (speed)
  57116. * @param worldMatrix is the world matrix of the particle system
  57117. * @param directionToUpdate is the direction vector to update with the result
  57118. * @param particle is the particle we are computed the direction for
  57119. */
  57120. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57121. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57122. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57123. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57124. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57125. direction.x += randX;
  57126. direction.y += randY;
  57127. direction.z += randZ;
  57128. direction.normalize();
  57129. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57130. };
  57131. /**
  57132. * Called by the particle System when the position is computed for the created particle.
  57133. * @param worldMatrix is the world matrix of the particle system
  57134. * @param positionToUpdate is the position vector to update with the result
  57135. * @param particle is the particle we are computed the position for
  57136. */
  57137. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57138. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57139. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57140. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57141. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57142. var randY = randRadius * Math.cos(theta);
  57143. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57144. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57145. };
  57146. /**
  57147. * Clones the current emitter and returns a copy of it
  57148. * @returns the new emitter
  57149. */
  57150. SphereParticleEmitter.prototype.clone = function () {
  57151. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57152. BABYLON.Tools.DeepCopy(this, newOne);
  57153. return newOne;
  57154. };
  57155. /**
  57156. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57157. * @param effect defines the update shader
  57158. */
  57159. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57160. effect.setFloat("radius", this.radius);
  57161. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57162. };
  57163. /**
  57164. * Returns a string to use to update the GPU particles update shader
  57165. * @returns a string containng the defines string
  57166. */
  57167. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57168. return "#define SPHEREEMITTER";
  57169. };
  57170. /**
  57171. * Returns the string "SphereParticleEmitter"
  57172. * @returns a string containing the class name
  57173. */
  57174. SphereParticleEmitter.prototype.getClassName = function () {
  57175. return "SphereParticleEmitter";
  57176. };
  57177. /**
  57178. * Serializes the particle system to a JSON object.
  57179. * @returns the JSON object
  57180. */
  57181. SphereParticleEmitter.prototype.serialize = function () {
  57182. var serializationObject = {};
  57183. serializationObject.type = this.getClassName();
  57184. serializationObject.radius = this.radius;
  57185. serializationObject.directionRandomizer = this.directionRandomizer;
  57186. return serializationObject;
  57187. };
  57188. /**
  57189. * Parse properties from a JSON object
  57190. * @param serializationObject defines the JSON object
  57191. */
  57192. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57193. this.radius = serializationObject.radius;
  57194. this.directionRandomizer = serializationObject.directionRandomizer;
  57195. };
  57196. return SphereParticleEmitter;
  57197. }());
  57198. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57199. /**
  57200. * Particle emitter emitting particles from the inside of a sphere.
  57201. * It emits the particles randomly between two vectors.
  57202. */
  57203. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57204. __extends(SphereDirectedParticleEmitter, _super);
  57205. /**
  57206. * Creates a new instance SphereDirectedParticleEmitter
  57207. * @param radius the radius of the emission sphere (1 by default)
  57208. * @param direction1 the min limit of the emission direction (up vector by default)
  57209. * @param direction2 the max limit of the emission direction (up vector by default)
  57210. */
  57211. function SphereDirectedParticleEmitter(radius,
  57212. /**
  57213. * The min limit of the emission direction.
  57214. */
  57215. direction1,
  57216. /**
  57217. * The max limit of the emission direction.
  57218. */
  57219. direction2) {
  57220. if (radius === void 0) { radius = 1; }
  57221. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57222. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57223. var _this = _super.call(this, radius) || this;
  57224. _this.direction1 = direction1;
  57225. _this.direction2 = direction2;
  57226. return _this;
  57227. }
  57228. /**
  57229. * Called by the particle System when the direction is computed for the created particle.
  57230. * @param emitPower is the power of the particle (speed)
  57231. * @param worldMatrix is the world matrix of the particle system
  57232. * @param directionToUpdate is the direction vector to update with the result
  57233. * @param particle is the particle we are computed the direction for
  57234. */
  57235. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57236. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57237. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57238. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57239. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57240. };
  57241. /**
  57242. * Clones the current emitter and returns a copy of it
  57243. * @returns the new emitter
  57244. */
  57245. SphereDirectedParticleEmitter.prototype.clone = function () {
  57246. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57247. BABYLON.Tools.DeepCopy(this, newOne);
  57248. return newOne;
  57249. };
  57250. /**
  57251. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57252. * @param effect defines the update shader
  57253. */
  57254. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57255. effect.setFloat("radius", this.radius);
  57256. effect.setVector3("direction1", this.direction1);
  57257. effect.setVector3("direction2", this.direction2);
  57258. };
  57259. /**
  57260. * Returns a string to use to update the GPU particles update shader
  57261. * @returns a string containng the defines string
  57262. */
  57263. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57264. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57265. };
  57266. /**
  57267. * Returns the string "SphereDirectedParticleEmitter"
  57268. * @returns a string containing the class name
  57269. */
  57270. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57271. return "SphereDirectedParticleEmitter";
  57272. };
  57273. /**
  57274. * Serializes the particle system to a JSON object.
  57275. * @returns the JSON object
  57276. */
  57277. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57278. var serializationObject = _super.prototype.serialize.call(this);
  57279. serializationObject.direction1 = this.direction1.asArray();
  57280. serializationObject.direction2 = this.direction2.asArray();
  57281. return serializationObject;
  57282. };
  57283. /**
  57284. * Parse properties from a JSON object
  57285. * @param serializationObject defines the JSON object
  57286. */
  57287. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57288. _super.prototype.parse.call(this, serializationObject);
  57289. this.direction1.copyFrom(serializationObject.direction1);
  57290. this.direction2.copyFrom(serializationObject.direction2);
  57291. };
  57292. return SphereDirectedParticleEmitter;
  57293. }(SphereParticleEmitter));
  57294. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57295. })(BABYLON || (BABYLON = {}));
  57296. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57297. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57298. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57299. s = arguments[i];
  57300. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57301. t[p] = s[p];
  57302. }
  57303. return t;
  57304. };
  57305. var BABYLON;
  57306. (function (BABYLON) {
  57307. /**
  57308. * This represents a GPU particle system in Babylon
  57309. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57310. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57311. */
  57312. var GPUParticleSystem = /** @class */ (function () {
  57313. /**
  57314. * Instantiates a GPU particle system.
  57315. * 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.
  57316. * @param name The name of the particle system
  57317. * @param capacity The max number of particles alive at the same time
  57318. * @param scene The scene the particle system belongs to
  57319. */
  57320. function GPUParticleSystem(name, options, scene) {
  57321. /**
  57322. * The emitter represents the Mesh or position we are attaching the particle system to.
  57323. */
  57324. this.emitter = null;
  57325. /**
  57326. * The rendering group used by the Particle system to chose when to render.
  57327. */
  57328. this.renderingGroupId = 0;
  57329. /**
  57330. * The layer mask we are rendering the particles through.
  57331. */
  57332. this.layerMask = 0x0FFFFFFF;
  57333. this._targetIndex = 0;
  57334. this._currentRenderId = -1;
  57335. this._started = false;
  57336. this._stopped = false;
  57337. this._timeDelta = 0;
  57338. this._attributesStrideSize = 14;
  57339. this._actualFrame = 0;
  57340. /**
  57341. * List of animations used by the particle system.
  57342. */
  57343. this.animations = [];
  57344. /**
  57345. * An event triggered when the system is disposed.
  57346. */
  57347. this.onDisposeObservable = new BABYLON.Observable();
  57348. /**
  57349. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57350. */
  57351. this.updateSpeed = 0.01;
  57352. /**
  57353. * The amount of time the particle system is running (depends of the overall update speed).
  57354. */
  57355. this.targetStopDuration = 0;
  57356. /**
  57357. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57358. */
  57359. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57360. /**
  57361. * Minimum life time of emitting particles.
  57362. */
  57363. this.minLifeTime = 1;
  57364. /**
  57365. * Maximum life time of emitting particles.
  57366. */
  57367. this.maxLifeTime = 1;
  57368. /**
  57369. * Minimum Size of emitting particles.
  57370. */
  57371. this.minSize = 1;
  57372. /**
  57373. * Maximum Size of emitting particles.
  57374. */
  57375. this.maxSize = 1;
  57376. /**
  57377. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57378. */
  57379. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57380. /**
  57381. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57382. */
  57383. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57384. /**
  57385. * Color the particle will have at the end of its lifetime.
  57386. */
  57387. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57388. /**
  57389. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57390. */
  57391. this.emitRate = 100;
  57392. /**
  57393. * You can use gravity if you want to give an orientation to your particles.
  57394. */
  57395. this.gravity = BABYLON.Vector3.Zero();
  57396. /**
  57397. * Minimum power of emitting particles.
  57398. */
  57399. this.minEmitPower = 1;
  57400. /**
  57401. * Maximum power of emitting particles.
  57402. */
  57403. this.maxEmitPower = 1;
  57404. /**
  57405. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57406. * to override the particles.
  57407. */
  57408. this.forceDepthWrite = false;
  57409. this.id = name;
  57410. this.name = name;
  57411. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57412. this._engine = this._scene.getEngine();
  57413. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57414. this._capacity = fullOptions.capacity;
  57415. this._activeCount = fullOptions.capacity;
  57416. this._currentActiveCount = 0;
  57417. this._scene.particleSystems.push(this);
  57418. this._updateEffectOptions = {
  57419. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57420. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57421. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57422. uniformBuffersNames: [],
  57423. samplers: ["randomSampler"],
  57424. defines: "",
  57425. fallbacks: null,
  57426. onCompiled: null,
  57427. onError: null,
  57428. indexParameters: null,
  57429. maxSimultaneousLights: 0,
  57430. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57431. };
  57432. // Random data
  57433. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57434. var d = [];
  57435. for (var i = 0; i < maxTextureSize; ++i) {
  57436. d.push(Math.random());
  57437. d.push(Math.random());
  57438. d.push(Math.random());
  57439. d.push(Math.random());
  57440. }
  57441. 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);
  57442. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57443. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57444. this._randomTextureSize = maxTextureSize;
  57445. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57446. }
  57447. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57448. /**
  57449. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57450. */
  57451. get: function () {
  57452. if (!BABYLON.Engine.LastCreatedEngine) {
  57453. return false;
  57454. }
  57455. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57456. },
  57457. enumerable: true,
  57458. configurable: true
  57459. });
  57460. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57461. /**
  57462. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57463. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57464. */
  57465. get: function () {
  57466. if (this.particleEmitterType.direction1) {
  57467. return this.particleEmitterType.direction1;
  57468. }
  57469. return BABYLON.Vector3.Zero();
  57470. },
  57471. set: function (value) {
  57472. if (this.particleEmitterType.direction1) {
  57473. this.particleEmitterType.direction1 = value;
  57474. }
  57475. },
  57476. enumerable: true,
  57477. configurable: true
  57478. });
  57479. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57480. /**
  57481. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57482. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57483. */
  57484. get: function () {
  57485. if (this.particleEmitterType.direction2) {
  57486. return this.particleEmitterType.direction2;
  57487. }
  57488. return BABYLON.Vector3.Zero();
  57489. },
  57490. set: function (value) {
  57491. if (this.particleEmitterType.direction2) {
  57492. this.particleEmitterType.direction2 = value;
  57493. }
  57494. },
  57495. enumerable: true,
  57496. configurable: true
  57497. });
  57498. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57499. /**
  57500. * 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.
  57501. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57502. */
  57503. get: function () {
  57504. if (this.particleEmitterType.minEmitBox) {
  57505. return this.particleEmitterType.minEmitBox;
  57506. }
  57507. return BABYLON.Vector3.Zero();
  57508. },
  57509. set: function (value) {
  57510. if (this.particleEmitterType.minEmitBox) {
  57511. this.particleEmitterType.minEmitBox = value;
  57512. }
  57513. },
  57514. enumerable: true,
  57515. configurable: true
  57516. });
  57517. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57518. /**
  57519. * 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.
  57520. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57521. */
  57522. get: function () {
  57523. if (this.particleEmitterType.maxEmitBox) {
  57524. return this.particleEmitterType.maxEmitBox;
  57525. }
  57526. return BABYLON.Vector3.Zero();
  57527. },
  57528. set: function (value) {
  57529. if (this.particleEmitterType.maxEmitBox) {
  57530. this.particleEmitterType.maxEmitBox = value;
  57531. }
  57532. },
  57533. enumerable: true,
  57534. configurable: true
  57535. });
  57536. /**
  57537. * Gets the maximum number of particles active at the same time.
  57538. * @returns The max number of active particles.
  57539. */
  57540. GPUParticleSystem.prototype.getCapacity = function () {
  57541. return this._capacity;
  57542. };
  57543. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57544. /**
  57545. * Gets or set the number of active particles
  57546. */
  57547. get: function () {
  57548. return this._activeCount;
  57549. },
  57550. set: function (value) {
  57551. this._activeCount = Math.min(value, this._capacity);
  57552. },
  57553. enumerable: true,
  57554. configurable: true
  57555. });
  57556. /**
  57557. * Is this system ready to be used/rendered
  57558. * @return true if the system is ready
  57559. */
  57560. GPUParticleSystem.prototype.isReady = function () {
  57561. if (!this._updateEffect) {
  57562. this._recreateUpdateEffect();
  57563. this._recreateRenderEffect();
  57564. return false;
  57565. }
  57566. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57567. return false;
  57568. }
  57569. return true;
  57570. };
  57571. /**
  57572. * Gets Wether the system has been started.
  57573. * @returns True if it has been started, otherwise false.
  57574. */
  57575. GPUParticleSystem.prototype.isStarted = function () {
  57576. return this._started;
  57577. };
  57578. /**
  57579. * Starts the particle system and begins to emit.
  57580. */
  57581. GPUParticleSystem.prototype.start = function () {
  57582. this._started = true;
  57583. this._stopped = false;
  57584. };
  57585. /**
  57586. * Stops the particle system.
  57587. */
  57588. GPUParticleSystem.prototype.stop = function () {
  57589. this._stopped = true;
  57590. };
  57591. /**
  57592. * Remove all active particles
  57593. */
  57594. GPUParticleSystem.prototype.reset = function () {
  57595. this._releaseBuffers();
  57596. this._releaseVAOs();
  57597. this._currentActiveCount = 0;
  57598. this._targetIndex = 0;
  57599. };
  57600. /**
  57601. * Returns the string "GPUParticleSystem"
  57602. * @returns a string containing the class name
  57603. */
  57604. GPUParticleSystem.prototype.getClassName = function () {
  57605. return "GPUParticleSystem";
  57606. };
  57607. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57608. var updateVertexBuffers = {};
  57609. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57610. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57611. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57612. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57613. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57614. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57615. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57616. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57617. this._engine.bindArrayBuffer(null);
  57618. return vao;
  57619. };
  57620. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57621. var renderVertexBuffers = {};
  57622. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57623. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57624. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57625. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57626. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57627. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57628. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57629. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57630. this._engine.bindArrayBuffer(null);
  57631. return vao;
  57632. };
  57633. GPUParticleSystem.prototype._initialize = function (force) {
  57634. if (force === void 0) { force = false; }
  57635. if (this._buffer0 && !force) {
  57636. return;
  57637. }
  57638. var engine = this._scene.getEngine();
  57639. var data = new Array();
  57640. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57641. // position
  57642. data.push(0.0);
  57643. data.push(0.0);
  57644. data.push(0.0);
  57645. // Age and life
  57646. data.push(0.0); // create the particle as a dead one to create a new one at start
  57647. data.push(0.0);
  57648. // Seed
  57649. data.push(Math.random());
  57650. // Size
  57651. data.push(0.0);
  57652. // color
  57653. data.push(0.0);
  57654. data.push(0.0);
  57655. data.push(0.0);
  57656. data.push(0.0);
  57657. // direction
  57658. data.push(0.0);
  57659. data.push(0.0);
  57660. data.push(0.0);
  57661. }
  57662. // Sprite data
  57663. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57664. -0.5, 0.5, 0, 1,
  57665. -0.5, -0.5, 0, 0,
  57666. 0.5, -0.5, 1, 0]);
  57667. // Buffers
  57668. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57669. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57670. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57671. // Update VAO
  57672. this._updateVAO = [];
  57673. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57674. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57675. // Render VAO
  57676. this._renderVAO = [];
  57677. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57678. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57679. // Links
  57680. this._sourceBuffer = this._buffer0;
  57681. this._targetBuffer = this._buffer1;
  57682. };
  57683. /** @hidden */
  57684. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57685. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57686. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57687. return;
  57688. }
  57689. this._updateEffectOptions.defines = defines;
  57690. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57691. };
  57692. /** @hidden */
  57693. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57694. var defines = "";
  57695. if (this._scene.clipPlane) {
  57696. defines = "\n#define CLIPPLANE";
  57697. }
  57698. if (this._renderEffect && this._renderEffect.defines === defines) {
  57699. return;
  57700. }
  57701. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57702. };
  57703. /**
  57704. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57705. */
  57706. GPUParticleSystem.prototype.animate = function () {
  57707. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57708. this._actualFrame += this._timeDelta;
  57709. if (!this._stopped) {
  57710. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57711. this.stop();
  57712. }
  57713. }
  57714. };
  57715. /**
  57716. * Renders the particle system in its current state.
  57717. * @returns the current number of particles
  57718. */
  57719. GPUParticleSystem.prototype.render = function () {
  57720. if (!this._started) {
  57721. return 0;
  57722. }
  57723. this._recreateUpdateEffect();
  57724. this._recreateRenderEffect();
  57725. if (!this.isReady()) {
  57726. return 0;
  57727. }
  57728. if (this._currentRenderId === this._scene.getRenderId()) {
  57729. return 0;
  57730. }
  57731. this._currentRenderId = this._scene.getRenderId();
  57732. // Get everything ready to render
  57733. this._initialize();
  57734. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57735. // Enable update effect
  57736. this._engine.enableEffect(this._updateEffect);
  57737. this._engine.setState(false);
  57738. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57739. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57740. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57741. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57742. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57743. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57744. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57745. this._updateEffect.setDirectColor4("color1", this.color1);
  57746. this._updateEffect.setDirectColor4("color2", this.color2);
  57747. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57748. this._updateEffect.setVector3("gravity", this.gravity);
  57749. if (this.particleEmitterType) {
  57750. this.particleEmitterType.applyToShader(this._updateEffect);
  57751. }
  57752. var emitterWM;
  57753. if (this.emitter.position) {
  57754. var emitterMesh = this.emitter;
  57755. emitterWM = emitterMesh.getWorldMatrix();
  57756. }
  57757. else {
  57758. var emitterPosition = this.emitter;
  57759. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57760. }
  57761. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57762. // Bind source VAO
  57763. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57764. // Update
  57765. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57766. this._engine.setRasterizerState(false);
  57767. this._engine.beginTransformFeedback();
  57768. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57769. this._engine.endTransformFeedback();
  57770. this._engine.setRasterizerState(true);
  57771. this._engine.bindTransformFeedbackBuffer(null);
  57772. // Enable render effect
  57773. this._engine.enableEffect(this._renderEffect);
  57774. var viewMatrix = this._scene.getViewMatrix();
  57775. this._renderEffect.setMatrix("view", viewMatrix);
  57776. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57777. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57778. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57779. if (this._scene.clipPlane) {
  57780. var clipPlane = this._scene.clipPlane;
  57781. var invView = viewMatrix.clone();
  57782. invView.invert();
  57783. this._renderEffect.setMatrix("invView", invView);
  57784. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57785. }
  57786. // Draw order
  57787. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57788. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57789. }
  57790. else {
  57791. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57792. }
  57793. if (this.forceDepthWrite) {
  57794. this._engine.setDepthWrite(true);
  57795. }
  57796. // Bind source VAO
  57797. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57798. // Render
  57799. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57800. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57801. // Switch VAOs
  57802. this._targetIndex++;
  57803. if (this._targetIndex === 2) {
  57804. this._targetIndex = 0;
  57805. }
  57806. // Switch buffers
  57807. var tmpBuffer = this._sourceBuffer;
  57808. this._sourceBuffer = this._targetBuffer;
  57809. this._targetBuffer = tmpBuffer;
  57810. return this._currentActiveCount;
  57811. };
  57812. /**
  57813. * Rebuilds the particle system
  57814. */
  57815. GPUParticleSystem.prototype.rebuild = function () {
  57816. this._initialize(true);
  57817. };
  57818. GPUParticleSystem.prototype._releaseBuffers = function () {
  57819. if (this._buffer0) {
  57820. this._buffer0.dispose();
  57821. this._buffer0 = null;
  57822. }
  57823. if (this._buffer1) {
  57824. this._buffer1.dispose();
  57825. this._buffer1 = null;
  57826. }
  57827. if (this._spriteBuffer) {
  57828. this._spriteBuffer.dispose();
  57829. this._spriteBuffer = null;
  57830. }
  57831. };
  57832. GPUParticleSystem.prototype._releaseVAOs = function () {
  57833. if (!this._updateVAO) {
  57834. return;
  57835. }
  57836. for (var index = 0; index < this._updateVAO.length; index++) {
  57837. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57838. }
  57839. this._updateVAO = [];
  57840. for (var index = 0; index < this._renderVAO.length; index++) {
  57841. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57842. }
  57843. this._renderVAO = [];
  57844. };
  57845. /**
  57846. * Disposes the particle system and free the associated resources
  57847. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57848. */
  57849. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57850. if (disposeTexture === void 0) { disposeTexture = true; }
  57851. var index = this._scene.particleSystems.indexOf(this);
  57852. if (index > -1) {
  57853. this._scene.particleSystems.splice(index, 1);
  57854. }
  57855. this._releaseBuffers();
  57856. this._releaseVAOs();
  57857. if (this._randomTexture) {
  57858. this._randomTexture.dispose();
  57859. this._randomTexture = null;
  57860. }
  57861. if (disposeTexture && this.particleTexture) {
  57862. this.particleTexture.dispose();
  57863. this.particleTexture = null;
  57864. }
  57865. // Callback
  57866. this.onDisposeObservable.notifyObservers(this);
  57867. this.onDisposeObservable.clear();
  57868. };
  57869. /**
  57870. * Clones the particle system.
  57871. * @param name The name of the cloned object
  57872. * @param newEmitter The new emitter to use
  57873. * @returns the cloned particle system
  57874. */
  57875. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57876. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57877. BABYLON.Tools.DeepCopy(this, result);
  57878. if (newEmitter === undefined) {
  57879. newEmitter = this.emitter;
  57880. }
  57881. result.emitter = newEmitter;
  57882. if (this.particleTexture) {
  57883. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57884. }
  57885. return result;
  57886. };
  57887. /**
  57888. * Serializes the particle system to a JSON object.
  57889. * @returns the JSON object
  57890. */
  57891. GPUParticleSystem.prototype.serialize = function () {
  57892. var serializationObject = {};
  57893. serializationObject.name = this.name;
  57894. serializationObject.id = this.id;
  57895. // Emitter
  57896. if (this.emitter.position) {
  57897. var emitterMesh = this.emitter;
  57898. serializationObject.emitterId = emitterMesh.id;
  57899. }
  57900. else {
  57901. var emitterPosition = this.emitter;
  57902. serializationObject.emitter = emitterPosition.asArray();
  57903. }
  57904. serializationObject.capacity = this.getCapacity();
  57905. if (this.particleTexture) {
  57906. serializationObject.textureName = this.particleTexture.name;
  57907. }
  57908. // Animations
  57909. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57910. // Particle system
  57911. serializationObject.activeParticleCount = this.activeParticleCount;
  57912. serializationObject.randomTextureSize = this._randomTextureSize;
  57913. serializationObject.minSize = this.minSize;
  57914. serializationObject.maxSize = this.maxSize;
  57915. serializationObject.minEmitPower = this.minEmitPower;
  57916. serializationObject.maxEmitPower = this.maxEmitPower;
  57917. serializationObject.minLifeTime = this.minLifeTime;
  57918. serializationObject.maxLifeTime = this.maxLifeTime;
  57919. serializationObject.emitRate = this.emitRate;
  57920. serializationObject.gravity = this.gravity.asArray();
  57921. serializationObject.color1 = this.color1.asArray();
  57922. serializationObject.color2 = this.color2.asArray();
  57923. serializationObject.colorDead = this.colorDead.asArray();
  57924. serializationObject.updateSpeed = this.updateSpeed;
  57925. serializationObject.targetStopDuration = this.targetStopDuration;
  57926. serializationObject.blendMode = this.blendMode;
  57927. // Emitter
  57928. if (this.particleEmitterType) {
  57929. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57930. }
  57931. return serializationObject;
  57932. };
  57933. /**
  57934. * Parses a JSON object to create a GPU particle system.
  57935. * @param parsedParticleSystem The JSON object to parse
  57936. * @param scene The scene to create the particle system in
  57937. * @param rootUrl The root url to use to load external dependencies like texture
  57938. * @returns the parsed GPU particle system
  57939. */
  57940. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57941. var name = parsedParticleSystem.name;
  57942. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57943. if (parsedParticleSystem.id) {
  57944. particleSystem.id = parsedParticleSystem.id;
  57945. }
  57946. // Texture
  57947. if (parsedParticleSystem.textureName) {
  57948. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57949. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57950. }
  57951. // Emitter
  57952. if (parsedParticleSystem.emitterId) {
  57953. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57954. }
  57955. else {
  57956. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57957. }
  57958. // Animations
  57959. if (parsedParticleSystem.animations) {
  57960. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57961. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57962. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57963. }
  57964. }
  57965. // Particle system
  57966. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57967. particleSystem.minSize = parsedParticleSystem.minSize;
  57968. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57969. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57970. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57971. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57972. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57973. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57974. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57975. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57976. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57977. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57978. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57979. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57980. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57981. // Emitter
  57982. if (parsedParticleSystem.particleEmitterType) {
  57983. var emitterType = void 0;
  57984. switch (parsedParticleSystem.particleEmitterType.type) {
  57985. case "SphereEmitter":
  57986. emitterType = new BABYLON.SphereParticleEmitter();
  57987. break;
  57988. case "SphereDirectedParticleEmitter":
  57989. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57990. break;
  57991. case "ConeEmitter":
  57992. emitterType = new BABYLON.ConeParticleEmitter();
  57993. break;
  57994. case "BoxEmitter":
  57995. default:
  57996. emitterType = new BABYLON.BoxParticleEmitter();
  57997. break;
  57998. }
  57999. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58000. particleSystem.particleEmitterType = emitterType;
  58001. }
  58002. return particleSystem;
  58003. };
  58004. return GPUParticleSystem;
  58005. }());
  58006. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58007. })(BABYLON || (BABYLON = {}));
  58008. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58009. var BABYLON;
  58010. (function (BABYLON) {
  58011. /**
  58012. * Represents one particle of a solid particle system.
  58013. */
  58014. var SolidParticle = /** @class */ (function () {
  58015. /**
  58016. * Creates a Solid Particle object.
  58017. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58018. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58019. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58020. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58021. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58022. * @param shapeId (integer) is the model shape identifier in the SPS.
  58023. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58024. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58025. */
  58026. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58027. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58028. /**
  58029. * particle global index
  58030. */
  58031. this.idx = 0;
  58032. /**
  58033. * The color of the particle
  58034. */
  58035. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58036. /**
  58037. * The world space position of the particle.
  58038. */
  58039. this.position = BABYLON.Vector3.Zero();
  58040. /**
  58041. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58042. */
  58043. this.rotation = BABYLON.Vector3.Zero();
  58044. /**
  58045. * The scaling of the particle.
  58046. */
  58047. this.scaling = BABYLON.Vector3.One();
  58048. /**
  58049. * The uvs of the particle.
  58050. */
  58051. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58052. /**
  58053. * The current speed of the particle.
  58054. */
  58055. this.velocity = BABYLON.Vector3.Zero();
  58056. /**
  58057. * The pivot point in the particle local space.
  58058. */
  58059. this.pivot = BABYLON.Vector3.Zero();
  58060. /**
  58061. * Must the particle be translated from its pivot point in its local space ?
  58062. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58063. * Default : false
  58064. */
  58065. this.translateFromPivot = false;
  58066. /**
  58067. * Is the particle active or not ?
  58068. */
  58069. this.alive = true;
  58070. /**
  58071. * Is the particle visible or not ?
  58072. */
  58073. this.isVisible = true;
  58074. /**
  58075. * Index of this particle in the global "positions" array (Internal use)
  58076. */
  58077. this._pos = 0;
  58078. /**
  58079. * Index of this particle in the global "indices" array (Internal use)
  58080. */
  58081. this._ind = 0;
  58082. /**
  58083. * ModelShape id of this particle
  58084. */
  58085. this.shapeId = 0;
  58086. /**
  58087. * Index of the particle in its shape id (Internal use)
  58088. */
  58089. this.idxInShape = 0;
  58090. /**
  58091. * Still set as invisible in order to skip useless computations (Internal use)
  58092. */
  58093. this._stillInvisible = false;
  58094. /**
  58095. * Last computed particle rotation matrix
  58096. */
  58097. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58098. /**
  58099. * Parent particle Id, if any.
  58100. * Default null.
  58101. */
  58102. this.parentId = null;
  58103. /**
  58104. * Internal global position in the SPS.
  58105. */
  58106. this._globalPosition = BABYLON.Vector3.Zero();
  58107. this.idx = particleIndex;
  58108. this._pos = positionIndex;
  58109. this._ind = indiceIndex;
  58110. this._model = model;
  58111. this.shapeId = shapeId;
  58112. this.idxInShape = idxInShape;
  58113. this._sps = sps;
  58114. if (modelBoundingInfo) {
  58115. this._modelBoundingInfo = modelBoundingInfo;
  58116. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58117. }
  58118. }
  58119. Object.defineProperty(SolidParticle.prototype, "scale", {
  58120. /**
  58121. * Legacy support, changed scale to scaling
  58122. */
  58123. get: function () {
  58124. return this.scaling;
  58125. },
  58126. /**
  58127. * Legacy support, changed scale to scaling
  58128. */
  58129. set: function (scale) {
  58130. this.scaling = scale;
  58131. },
  58132. enumerable: true,
  58133. configurable: true
  58134. });
  58135. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58136. /**
  58137. * Legacy support, changed quaternion to rotationQuaternion
  58138. */
  58139. get: function () {
  58140. return this.rotationQuaternion;
  58141. },
  58142. /**
  58143. * Legacy support, changed quaternion to rotationQuaternion
  58144. */
  58145. set: function (q) {
  58146. this.rotationQuaternion = q;
  58147. },
  58148. enumerable: true,
  58149. configurable: true
  58150. });
  58151. /**
  58152. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58153. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58154. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58155. * @returns true if it intersects
  58156. */
  58157. SolidParticle.prototype.intersectsMesh = function (target) {
  58158. if (!this._boundingInfo || !target._boundingInfo) {
  58159. return false;
  58160. }
  58161. if (this._sps._bSphereOnly) {
  58162. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58163. }
  58164. return this._boundingInfo.intersects(target._boundingInfo, false);
  58165. };
  58166. return SolidParticle;
  58167. }());
  58168. BABYLON.SolidParticle = SolidParticle;
  58169. /**
  58170. * Represents the shape of the model used by one particle of a solid particle system.
  58171. * SPS internal tool, don't use it manually.
  58172. */
  58173. var ModelShape = /** @class */ (function () {
  58174. /**
  58175. * 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.
  58176. * SPS internal tool, don't use it manually.
  58177. * @hidden
  58178. */
  58179. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58180. /**
  58181. * length of the shape in the model indices array (internal use)
  58182. */
  58183. this._indicesLength = 0;
  58184. this.shapeID = id;
  58185. this._shape = shape;
  58186. this._indicesLength = indicesLength;
  58187. this._shapeUV = shapeUV;
  58188. this._positionFunction = posFunction;
  58189. this._vertexFunction = vtxFunction;
  58190. }
  58191. return ModelShape;
  58192. }());
  58193. BABYLON.ModelShape = ModelShape;
  58194. /**
  58195. * Represents a Depth Sorted Particle in the solid particle system.
  58196. */
  58197. var DepthSortedParticle = /** @class */ (function () {
  58198. function DepthSortedParticle() {
  58199. /**
  58200. * Index of the particle in the "indices" array
  58201. */
  58202. this.ind = 0;
  58203. /**
  58204. * Length of the particle shape in the "indices" array
  58205. */
  58206. this.indicesLength = 0;
  58207. /**
  58208. * Squared distance from the particle to the camera
  58209. */
  58210. this.sqDistance = 0.0;
  58211. }
  58212. return DepthSortedParticle;
  58213. }());
  58214. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58215. })(BABYLON || (BABYLON = {}));
  58216. //# sourceMappingURL=babylon.solidParticle.js.map
  58217. var BABYLON;
  58218. (function (BABYLON) {
  58219. /**
  58220. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58221. *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.
  58222. * The SPS is also a particle system. It provides some methods to manage the particles.
  58223. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58224. *
  58225. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58226. */
  58227. var SolidParticleSystem = /** @class */ (function () {
  58228. /**
  58229. * Creates a SPS (Solid Particle System) object.
  58230. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58231. * @param scene (Scene) is the scene in which the SPS is added.
  58232. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58233. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58234. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58235. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58236. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58237. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58238. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58239. */
  58240. function SolidParticleSystem(name, scene, options) {
  58241. /**
  58242. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58243. * Example : var p = SPS.particles[i];
  58244. */
  58245. this.particles = new Array();
  58246. /**
  58247. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58248. */
  58249. this.nbParticles = 0;
  58250. /**
  58251. * If the particles must ever face the camera (default false). Useful for planar particles.
  58252. */
  58253. this.billboard = false;
  58254. /**
  58255. * Recompute normals when adding a shape
  58256. */
  58257. this.recomputeNormals = true;
  58258. /**
  58259. * This a counter ofr your own usage. It's not set by any SPS functions.
  58260. */
  58261. this.counter = 0;
  58262. /**
  58263. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58264. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58265. */
  58266. this.vars = {};
  58267. /**
  58268. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58269. */
  58270. this._bSphereOnly = false;
  58271. /**
  58272. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58273. */
  58274. this._bSphereRadiusFactor = 1.0;
  58275. this._positions = new Array();
  58276. this._indices = new Array();
  58277. this._normals = new Array();
  58278. this._colors = new Array();
  58279. this._uvs = new Array();
  58280. this._index = 0; // indices index
  58281. this._updatable = true;
  58282. this._pickable = false;
  58283. this._isVisibilityBoxLocked = false;
  58284. this._alwaysVisible = false;
  58285. this._depthSort = false;
  58286. this._shapeCounter = 0;
  58287. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58288. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58289. this._computeParticleColor = true;
  58290. this._computeParticleTexture = true;
  58291. this._computeParticleRotation = true;
  58292. this._computeParticleVertex = false;
  58293. this._computeBoundingBox = false;
  58294. this._depthSortParticles = true;
  58295. this._cam_axisZ = BABYLON.Vector3.Zero();
  58296. this._cam_axisY = BABYLON.Vector3.Zero();
  58297. this._cam_axisX = BABYLON.Vector3.Zero();
  58298. this._axisZ = BABYLON.Axis.Z;
  58299. this._camDir = BABYLON.Vector3.Zero();
  58300. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58301. this._rotMatrix = new BABYLON.Matrix();
  58302. this._invertMatrix = new BABYLON.Matrix();
  58303. this._rotated = BABYLON.Vector3.Zero();
  58304. this._quaternion = new BABYLON.Quaternion();
  58305. this._vertex = BABYLON.Vector3.Zero();
  58306. this._normal = BABYLON.Vector3.Zero();
  58307. this._yaw = 0.0;
  58308. this._pitch = 0.0;
  58309. this._roll = 0.0;
  58310. this._halfroll = 0.0;
  58311. this._halfpitch = 0.0;
  58312. this._halfyaw = 0.0;
  58313. this._sinRoll = 0.0;
  58314. this._cosRoll = 0.0;
  58315. this._sinPitch = 0.0;
  58316. this._cosPitch = 0.0;
  58317. this._sinYaw = 0.0;
  58318. this._cosYaw = 0.0;
  58319. this._mustUnrotateFixedNormals = false;
  58320. this._minimum = BABYLON.Vector3.Zero();
  58321. this._maximum = BABYLON.Vector3.Zero();
  58322. this._minBbox = BABYLON.Vector3.Zero();
  58323. this._maxBbox = BABYLON.Vector3.Zero();
  58324. this._particlesIntersect = false;
  58325. this._depthSortFunction = function (p1, p2) {
  58326. return (p2.sqDistance - p1.sqDistance);
  58327. };
  58328. this._needs32Bits = false;
  58329. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58330. this._scaledPivot = BABYLON.Vector3.Zero();
  58331. this._particleHasParent = false;
  58332. this.name = name;
  58333. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58334. this._camera = scene.activeCamera;
  58335. this._pickable = options ? options.isPickable : false;
  58336. this._depthSort = options ? options.enableDepthSort : false;
  58337. this._particlesIntersect = options ? options.particleIntersection : false;
  58338. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58339. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58340. if (options && options.updatable) {
  58341. this._updatable = options.updatable;
  58342. }
  58343. else {
  58344. this._updatable = true;
  58345. }
  58346. if (this._pickable) {
  58347. this.pickedParticles = [];
  58348. }
  58349. if (this._depthSort) {
  58350. this.depthSortedParticles = [];
  58351. }
  58352. }
  58353. /**
  58354. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58355. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58356. * @returns the created mesh
  58357. */
  58358. SolidParticleSystem.prototype.buildMesh = function () {
  58359. if (this.nbParticles === 0) {
  58360. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58361. this.addShape(triangle, 1);
  58362. triangle.dispose();
  58363. }
  58364. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58365. this._positions32 = new Float32Array(this._positions);
  58366. this._uvs32 = new Float32Array(this._uvs);
  58367. this._colors32 = new Float32Array(this._colors);
  58368. if (this.recomputeNormals) {
  58369. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58370. }
  58371. this._normals32 = new Float32Array(this._normals);
  58372. this._fixedNormal32 = new Float32Array(this._normals);
  58373. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58374. this._unrotateFixedNormals();
  58375. }
  58376. var vertexData = new BABYLON.VertexData();
  58377. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58378. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58379. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58380. if (this._uvs32.length > 0) {
  58381. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58382. }
  58383. if (this._colors32.length > 0) {
  58384. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58385. }
  58386. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58387. vertexData.applyToMesh(mesh, this._updatable);
  58388. this.mesh = mesh;
  58389. this.mesh.isPickable = this._pickable;
  58390. // free memory
  58391. if (!this._depthSort) {
  58392. this._indices = null;
  58393. }
  58394. this._positions = null;
  58395. this._normals = null;
  58396. this._uvs = null;
  58397. this._colors = null;
  58398. if (!this._updatable) {
  58399. this.particles.length = 0;
  58400. }
  58401. return mesh;
  58402. };
  58403. /**
  58404. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58405. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58406. * Thus the particles generated from `digest()` have their property `position` set yet.
  58407. * @param mesh ( Mesh ) is the mesh to be digested
  58408. * @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
  58409. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58410. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58411. * @returns the current SPS
  58412. */
  58413. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58414. var size = (options && options.facetNb) || 1;
  58415. var number = (options && options.number) || 0;
  58416. var delta = (options && options.delta) || 0;
  58417. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58418. var meshInd = mesh.getIndices();
  58419. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58420. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58421. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58422. var f = 0; // facet counter
  58423. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58424. // compute size from number
  58425. if (number) {
  58426. number = (number > totalFacets) ? totalFacets : number;
  58427. size = Math.round(totalFacets / number);
  58428. delta = 0;
  58429. }
  58430. else {
  58431. size = (size > totalFacets) ? totalFacets : size;
  58432. }
  58433. var facetPos = []; // submesh positions
  58434. var facetInd = []; // submesh indices
  58435. var facetUV = []; // submesh UV
  58436. var facetCol = []; // submesh colors
  58437. var barycenter = BABYLON.Vector3.Zero();
  58438. var sizeO = size;
  58439. while (f < totalFacets) {
  58440. size = sizeO + Math.floor((1 + delta) * Math.random());
  58441. if (f > totalFacets - size) {
  58442. size = totalFacets - f;
  58443. }
  58444. // reset temp arrays
  58445. facetPos.length = 0;
  58446. facetInd.length = 0;
  58447. facetUV.length = 0;
  58448. facetCol.length = 0;
  58449. // iterate over "size" facets
  58450. var fi = 0;
  58451. for (var j = f * 3; j < (f + size) * 3; j++) {
  58452. facetInd.push(fi);
  58453. var i = meshInd[j];
  58454. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58455. if (meshUV) {
  58456. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58457. }
  58458. if (meshCol) {
  58459. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58460. }
  58461. fi++;
  58462. }
  58463. // create a model shape for each single particle
  58464. var idx = this.nbParticles;
  58465. var shape = this._posToShape(facetPos);
  58466. var shapeUV = this._uvsToShapeUV(facetUV);
  58467. // compute the barycenter of the shape
  58468. var v;
  58469. for (v = 0; v < shape.length; v++) {
  58470. barycenter.addInPlace(shape[v]);
  58471. }
  58472. barycenter.scaleInPlace(1 / shape.length);
  58473. // shift the shape from its barycenter to the origin
  58474. for (v = 0; v < shape.length; v++) {
  58475. shape[v].subtractInPlace(barycenter);
  58476. }
  58477. var bInfo;
  58478. if (this._particlesIntersect) {
  58479. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58480. }
  58481. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58482. // add the particle in the SPS
  58483. var currentPos = this._positions.length;
  58484. var currentInd = this._indices.length;
  58485. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58486. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58487. // initialize the particle position
  58488. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58489. this._index += shape.length;
  58490. idx++;
  58491. this.nbParticles++;
  58492. this._shapeCounter++;
  58493. f += size;
  58494. }
  58495. return this;
  58496. };
  58497. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58498. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58499. var index = 0;
  58500. var idx = 0;
  58501. for (var p = 0; p < this.particles.length; p++) {
  58502. this._particle = this.particles[p];
  58503. this._shape = this._particle._model._shape;
  58504. if (this._particle.rotationQuaternion) {
  58505. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58506. }
  58507. else {
  58508. this._yaw = this._particle.rotation.y;
  58509. this._pitch = this._particle.rotation.x;
  58510. this._roll = this._particle.rotation.z;
  58511. this._quaternionRotationYPR();
  58512. }
  58513. this._quaternionToRotationMatrix();
  58514. this._rotMatrix.invertToRef(this._invertMatrix);
  58515. for (var pt = 0; pt < this._shape.length; pt++) {
  58516. idx = index + pt * 3;
  58517. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58518. this._fixedNormal32[idx] = this._normal.x;
  58519. this._fixedNormal32[idx + 1] = this._normal.y;
  58520. this._fixedNormal32[idx + 2] = this._normal.z;
  58521. }
  58522. index = idx + 3;
  58523. }
  58524. };
  58525. //reset copy
  58526. SolidParticleSystem.prototype._resetCopy = function () {
  58527. this._copy.position.x = 0;
  58528. this._copy.position.y = 0;
  58529. this._copy.position.z = 0;
  58530. this._copy.rotation.x = 0;
  58531. this._copy.rotation.y = 0;
  58532. this._copy.rotation.z = 0;
  58533. this._copy.rotationQuaternion = null;
  58534. this._copy.scaling.x = 1.0;
  58535. this._copy.scaling.y = 1.0;
  58536. this._copy.scaling.z = 1.0;
  58537. this._copy.uvs.x = 0;
  58538. this._copy.uvs.y = 0;
  58539. this._copy.uvs.z = 1.0;
  58540. this._copy.uvs.w = 1.0;
  58541. this._copy.color = null;
  58542. this._copy.translateFromPivot = false;
  58543. };
  58544. // _meshBuilder : inserts the shape model in the global SPS mesh
  58545. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58546. var i;
  58547. var u = 0;
  58548. var c = 0;
  58549. var n = 0;
  58550. this._resetCopy();
  58551. if (options && options.positionFunction) { // call to custom positionFunction
  58552. options.positionFunction(this._copy, idx, idxInShape);
  58553. this._mustUnrotateFixedNormals = true;
  58554. }
  58555. if (this._copy.rotationQuaternion) {
  58556. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58557. }
  58558. else {
  58559. this._yaw = this._copy.rotation.y;
  58560. this._pitch = this._copy.rotation.x;
  58561. this._roll = this._copy.rotation.z;
  58562. this._quaternionRotationYPR();
  58563. }
  58564. this._quaternionToRotationMatrix();
  58565. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58566. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58567. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58568. if (this._copy.translateFromPivot) {
  58569. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58570. }
  58571. else {
  58572. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58573. }
  58574. for (i = 0; i < shape.length; i++) {
  58575. this._vertex.x = shape[i].x;
  58576. this._vertex.y = shape[i].y;
  58577. this._vertex.z = shape[i].z;
  58578. if (options && options.vertexFunction) {
  58579. options.vertexFunction(this._copy, this._vertex, i);
  58580. }
  58581. this._vertex.x *= this._copy.scaling.x;
  58582. this._vertex.y *= this._copy.scaling.y;
  58583. this._vertex.z *= this._copy.scaling.z;
  58584. this._vertex.x -= this._scaledPivot.x;
  58585. this._vertex.y -= this._scaledPivot.y;
  58586. this._vertex.z -= this._scaledPivot.z;
  58587. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58588. this._rotated.addInPlace(this._pivotBackTranslation);
  58589. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58590. if (meshUV) {
  58591. 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);
  58592. u += 2;
  58593. }
  58594. if (this._copy.color) {
  58595. this._color = this._copy.color;
  58596. }
  58597. else if (meshCol && meshCol[c] !== undefined) {
  58598. this._color.r = meshCol[c];
  58599. this._color.g = meshCol[c + 1];
  58600. this._color.b = meshCol[c + 2];
  58601. this._color.a = meshCol[c + 3];
  58602. }
  58603. else {
  58604. this._color.r = 1.0;
  58605. this._color.g = 1.0;
  58606. this._color.b = 1.0;
  58607. this._color.a = 1.0;
  58608. }
  58609. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58610. c += 4;
  58611. if (!this.recomputeNormals && meshNor) {
  58612. this._normal.x = meshNor[n];
  58613. this._normal.y = meshNor[n + 1];
  58614. this._normal.z = meshNor[n + 2];
  58615. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58616. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58617. n += 3;
  58618. }
  58619. }
  58620. for (i = 0; i < meshInd.length; i++) {
  58621. var current_ind = p + meshInd[i];
  58622. indices.push(current_ind);
  58623. if (current_ind > 65535) {
  58624. this._needs32Bits = true;
  58625. }
  58626. }
  58627. if (this._pickable) {
  58628. var nbfaces = meshInd.length / 3;
  58629. for (i = 0; i < nbfaces; i++) {
  58630. this.pickedParticles.push({ idx: idx, faceId: i });
  58631. }
  58632. }
  58633. if (this._depthSort) {
  58634. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58635. }
  58636. return this._copy;
  58637. };
  58638. // returns a shape array from positions array
  58639. SolidParticleSystem.prototype._posToShape = function (positions) {
  58640. var shape = [];
  58641. for (var i = 0; i < positions.length; i += 3) {
  58642. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58643. }
  58644. return shape;
  58645. };
  58646. // returns a shapeUV array from a Vector4 uvs
  58647. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58648. var shapeUV = [];
  58649. if (uvs) {
  58650. for (var i = 0; i < uvs.length; i++)
  58651. shapeUV.push(uvs[i]);
  58652. }
  58653. return shapeUV;
  58654. };
  58655. // adds a new particle object in the particles array
  58656. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58657. if (bInfo === void 0) { bInfo = null; }
  58658. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58659. this.particles.push(sp);
  58660. return sp;
  58661. };
  58662. /**
  58663. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58664. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58665. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58666. * @param nb (positive integer) the number of particles to be created from this model
  58667. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58668. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58669. * @returns the number of shapes in the system
  58670. */
  58671. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58672. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58673. var meshInd = mesh.getIndices();
  58674. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58675. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58676. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58677. var bbInfo;
  58678. if (this._particlesIntersect) {
  58679. bbInfo = mesh.getBoundingInfo();
  58680. }
  58681. var shape = this._posToShape(meshPos);
  58682. var shapeUV = this._uvsToShapeUV(meshUV);
  58683. var posfunc = options ? options.positionFunction : null;
  58684. var vtxfunc = options ? options.vertexFunction : null;
  58685. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58686. // particles
  58687. var sp;
  58688. var currentCopy;
  58689. var idx = this.nbParticles;
  58690. for (var i = 0; i < nb; i++) {
  58691. var currentPos = this._positions.length;
  58692. var currentInd = this._indices.length;
  58693. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58694. if (this._updatable) {
  58695. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58696. sp.position.copyFrom(currentCopy.position);
  58697. sp.rotation.copyFrom(currentCopy.rotation);
  58698. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58699. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58700. }
  58701. if (currentCopy.color && sp.color) {
  58702. sp.color.copyFrom(currentCopy.color);
  58703. }
  58704. sp.scaling.copyFrom(currentCopy.scaling);
  58705. sp.uvs.copyFrom(currentCopy.uvs);
  58706. }
  58707. this._index += shape.length;
  58708. idx++;
  58709. }
  58710. this.nbParticles += nb;
  58711. this._shapeCounter++;
  58712. return this._shapeCounter - 1;
  58713. };
  58714. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58715. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58716. this._resetCopy();
  58717. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58718. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58719. }
  58720. if (this._copy.rotationQuaternion) {
  58721. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58722. }
  58723. else {
  58724. this._yaw = this._copy.rotation.y;
  58725. this._pitch = this._copy.rotation.x;
  58726. this._roll = this._copy.rotation.z;
  58727. this._quaternionRotationYPR();
  58728. }
  58729. this._quaternionToRotationMatrix();
  58730. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58731. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58732. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58733. if (this._copy.translateFromPivot) {
  58734. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58735. }
  58736. else {
  58737. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58738. }
  58739. this._shape = particle._model._shape;
  58740. for (var pt = 0; pt < this._shape.length; pt++) {
  58741. this._vertex.x = this._shape[pt].x;
  58742. this._vertex.y = this._shape[pt].y;
  58743. this._vertex.z = this._shape[pt].z;
  58744. if (particle._model._vertexFunction) {
  58745. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58746. }
  58747. this._vertex.x *= this._copy.scaling.x;
  58748. this._vertex.y *= this._copy.scaling.y;
  58749. this._vertex.z *= this._copy.scaling.z;
  58750. this._vertex.x -= this._scaledPivot.x;
  58751. this._vertex.y -= this._scaledPivot.y;
  58752. this._vertex.z -= this._scaledPivot.z;
  58753. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58754. this._rotated.addInPlace(this._pivotBackTranslation);
  58755. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58756. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58757. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58758. }
  58759. particle.position.x = 0.0;
  58760. particle.position.y = 0.0;
  58761. particle.position.z = 0.0;
  58762. particle.rotation.x = 0.0;
  58763. particle.rotation.y = 0.0;
  58764. particle.rotation.z = 0.0;
  58765. particle.rotationQuaternion = null;
  58766. particle.scaling.x = 1.0;
  58767. particle.scaling.y = 1.0;
  58768. particle.scaling.z = 1.0;
  58769. particle.uvs.x = 0.0;
  58770. particle.uvs.y = 0.0;
  58771. particle.uvs.z = 1.0;
  58772. particle.uvs.w = 1.0;
  58773. particle.pivot.x = 0.0;
  58774. particle.pivot.y = 0.0;
  58775. particle.pivot.z = 0.0;
  58776. particle.translateFromPivot = false;
  58777. particle.parentId = null;
  58778. };
  58779. /**
  58780. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58781. * @returns the SPS.
  58782. */
  58783. SolidParticleSystem.prototype.rebuildMesh = function () {
  58784. for (var p = 0; p < this.particles.length; p++) {
  58785. this._rebuildParticle(this.particles[p]);
  58786. }
  58787. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58788. return this;
  58789. };
  58790. /**
  58791. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58792. * This method calls `updateParticle()` for each particle of the SPS.
  58793. * For an animated SPS, it is usually called within the render loop.
  58794. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58795. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58796. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58797. * @returns the SPS.
  58798. */
  58799. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58800. if (start === void 0) { start = 0; }
  58801. if (end === void 0) { end = this.nbParticles - 1; }
  58802. if (update === void 0) { update = true; }
  58803. if (!this._updatable) {
  58804. return this;
  58805. }
  58806. // custom beforeUpdate
  58807. this.beforeUpdateParticles(start, end, update);
  58808. this._cam_axisX.x = 1.0;
  58809. this._cam_axisX.y = 0.0;
  58810. this._cam_axisX.z = 0.0;
  58811. this._cam_axisY.x = 0.0;
  58812. this._cam_axisY.y = 1.0;
  58813. this._cam_axisY.z = 0.0;
  58814. this._cam_axisZ.x = 0.0;
  58815. this._cam_axisZ.y = 0.0;
  58816. this._cam_axisZ.z = 1.0;
  58817. // cases when the World Matrix is to be computed first
  58818. if (this.billboard || this._depthSort) {
  58819. this.mesh.computeWorldMatrix(true);
  58820. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58821. }
  58822. // if the particles will always face the camera
  58823. if (this.billboard) {
  58824. // compute the camera position and un-rotate it by the current mesh rotation
  58825. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58826. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58827. this._cam_axisZ.normalize();
  58828. // same for camera up vector extracted from the cam view matrix
  58829. var view = this._camera.getViewMatrix(true);
  58830. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58831. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58832. this._cam_axisY.normalize();
  58833. this._cam_axisX.normalize();
  58834. }
  58835. // if depthSort, compute the camera global position in the mesh local system
  58836. if (this._depthSort) {
  58837. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58838. }
  58839. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58840. var idx = 0; // current position index in the global array positions32
  58841. var index = 0; // position start index in the global array positions32 of the current particle
  58842. var colidx = 0; // current color index in the global array colors32
  58843. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58844. var uvidx = 0; // current uv index in the global array uvs32
  58845. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58846. var pt = 0; // current index in the particle model shape
  58847. if (this.mesh.isFacetDataEnabled) {
  58848. this._computeBoundingBox = true;
  58849. }
  58850. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58851. if (this._computeBoundingBox) {
  58852. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58853. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58854. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58855. }
  58856. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58857. if (this.mesh._boundingInfo) {
  58858. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58859. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58860. }
  58861. }
  58862. }
  58863. // particle loop
  58864. index = this.particles[start]._pos;
  58865. var vpos = (index / 3) | 0;
  58866. colorIndex = vpos * 4;
  58867. uvIndex = vpos * 2;
  58868. for (var p = start; p <= end; p++) {
  58869. this._particle = this.particles[p];
  58870. this._shape = this._particle._model._shape;
  58871. this._shapeUV = this._particle._model._shapeUV;
  58872. // call to custom user function to update the particle properties
  58873. this.updateParticle(this._particle);
  58874. // camera-particle distance for depth sorting
  58875. if (this._depthSort && this._depthSortParticles) {
  58876. var dsp = this.depthSortedParticles[p];
  58877. dsp.ind = this._particle._ind;
  58878. dsp.indicesLength = this._particle._model._indicesLength;
  58879. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58880. }
  58881. // skip the computations for inactive or already invisible particles
  58882. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58883. // increment indexes for the next particle
  58884. pt = this._shape.length;
  58885. index += pt * 3;
  58886. colorIndex += pt * 4;
  58887. uvIndex += pt * 2;
  58888. continue;
  58889. }
  58890. if (this._particle.isVisible) {
  58891. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58892. this._particleHasParent = (this._particle.parentId !== null);
  58893. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58894. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58895. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58896. // particle rotation matrix
  58897. if (this.billboard) {
  58898. this._particle.rotation.x = 0.0;
  58899. this._particle.rotation.y = 0.0;
  58900. }
  58901. if (this._computeParticleRotation || this.billboard) {
  58902. if (this._particle.rotationQuaternion) {
  58903. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58904. }
  58905. else {
  58906. this._yaw = this._particle.rotation.y;
  58907. this._pitch = this._particle.rotation.x;
  58908. this._roll = this._particle.rotation.z;
  58909. this._quaternionRotationYPR();
  58910. }
  58911. this._quaternionToRotationMatrix();
  58912. }
  58913. if (this._particleHasParent) {
  58914. this._parent = this.particles[this._particle.parentId];
  58915. 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];
  58916. 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];
  58917. 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];
  58918. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58919. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58920. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58921. if (this._computeParticleRotation || this.billboard) {
  58922. 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];
  58923. 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];
  58924. 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];
  58925. 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];
  58926. 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];
  58927. 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];
  58928. 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];
  58929. 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];
  58930. 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];
  58931. }
  58932. }
  58933. else {
  58934. this._particle._globalPosition.x = this._particle.position.x;
  58935. this._particle._globalPosition.y = this._particle.position.y;
  58936. this._particle._globalPosition.z = this._particle.position.z;
  58937. if (this._computeParticleRotation || this.billboard) {
  58938. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58939. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58940. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58941. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58942. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58943. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58944. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58945. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58946. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58947. }
  58948. }
  58949. if (this._particle.translateFromPivot) {
  58950. this._pivotBackTranslation.x = 0.0;
  58951. this._pivotBackTranslation.y = 0.0;
  58952. this._pivotBackTranslation.z = 0.0;
  58953. }
  58954. else {
  58955. this._pivotBackTranslation.x = this._scaledPivot.x;
  58956. this._pivotBackTranslation.y = this._scaledPivot.y;
  58957. this._pivotBackTranslation.z = this._scaledPivot.z;
  58958. }
  58959. // particle vertex loop
  58960. for (pt = 0; pt < this._shape.length; pt++) {
  58961. idx = index + pt * 3;
  58962. colidx = colorIndex + pt * 4;
  58963. uvidx = uvIndex + pt * 2;
  58964. this._vertex.x = this._shape[pt].x;
  58965. this._vertex.y = this._shape[pt].y;
  58966. this._vertex.z = this._shape[pt].z;
  58967. if (this._computeParticleVertex) {
  58968. this.updateParticleVertex(this._particle, this._vertex, pt);
  58969. }
  58970. // positions
  58971. this._vertex.x *= this._particle.scaling.x;
  58972. this._vertex.y *= this._particle.scaling.y;
  58973. this._vertex.z *= this._particle.scaling.z;
  58974. this._vertex.x -= this._scaledPivot.x;
  58975. this._vertex.y -= this._scaledPivot.y;
  58976. this._vertex.z -= this._scaledPivot.z;
  58977. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58978. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58979. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58980. this._rotated.x += this._pivotBackTranslation.x;
  58981. this._rotated.y += this._pivotBackTranslation.y;
  58982. this._rotated.z += this._pivotBackTranslation.z;
  58983. 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;
  58984. 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;
  58985. 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;
  58986. if (this._computeBoundingBox) {
  58987. if (this._positions32[idx] < this._minimum.x) {
  58988. this._minimum.x = this._positions32[idx];
  58989. }
  58990. if (this._positions32[idx] > this._maximum.x) {
  58991. this._maximum.x = this._positions32[idx];
  58992. }
  58993. if (this._positions32[idx + 1] < this._minimum.y) {
  58994. this._minimum.y = this._positions32[idx + 1];
  58995. }
  58996. if (this._positions32[idx + 1] > this._maximum.y) {
  58997. this._maximum.y = this._positions32[idx + 1];
  58998. }
  58999. if (this._positions32[idx + 2] < this._minimum.z) {
  59000. this._minimum.z = this._positions32[idx + 2];
  59001. }
  59002. if (this._positions32[idx + 2] > this._maximum.z) {
  59003. this._maximum.z = this._positions32[idx + 2];
  59004. }
  59005. }
  59006. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59007. if (!this._computeParticleVertex) {
  59008. this._normal.x = this._fixedNormal32[idx];
  59009. this._normal.y = this._fixedNormal32[idx + 1];
  59010. this._normal.z = this._fixedNormal32[idx + 2];
  59011. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59012. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59013. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59014. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59015. 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;
  59016. 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;
  59017. }
  59018. if (this._computeParticleColor && this._particle.color) {
  59019. this._colors32[colidx] = this._particle.color.r;
  59020. this._colors32[colidx + 1] = this._particle.color.g;
  59021. this._colors32[colidx + 2] = this._particle.color.b;
  59022. this._colors32[colidx + 3] = this._particle.color.a;
  59023. }
  59024. if (this._computeParticleTexture) {
  59025. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59026. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59027. }
  59028. }
  59029. }
  59030. // particle just set invisible : scaled to zero and positioned at the origin
  59031. else {
  59032. this._particle._stillInvisible = true; // mark the particle as invisible
  59033. for (pt = 0; pt < this._shape.length; pt++) {
  59034. idx = index + pt * 3;
  59035. colidx = colorIndex + pt * 4;
  59036. uvidx = uvIndex + pt * 2;
  59037. this._positions32[idx] = 0.0;
  59038. this._positions32[idx + 1] = 0.0;
  59039. this._positions32[idx + 2] = 0.0;
  59040. this._normals32[idx] = 0.0;
  59041. this._normals32[idx + 1] = 0.0;
  59042. this._normals32[idx + 2] = 0.0;
  59043. if (this._computeParticleColor && this._particle.color) {
  59044. this._colors32[colidx] = this._particle.color.r;
  59045. this._colors32[colidx + 1] = this._particle.color.g;
  59046. this._colors32[colidx + 2] = this._particle.color.b;
  59047. this._colors32[colidx + 3] = this._particle.color.a;
  59048. }
  59049. if (this._computeParticleTexture) {
  59050. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59051. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59052. }
  59053. }
  59054. }
  59055. // if the particle intersections must be computed : update the bbInfo
  59056. if (this._particlesIntersect) {
  59057. var bInfo = this._particle._boundingInfo;
  59058. var bBox = bInfo.boundingBox;
  59059. var bSphere = bInfo.boundingSphere;
  59060. if (!this._bSphereOnly) {
  59061. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59062. for (var b = 0; b < bBox.vectors.length; b++) {
  59063. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59064. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59065. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59066. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59067. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59068. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59069. 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;
  59070. 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;
  59071. 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;
  59072. }
  59073. bBox._update(this.mesh._worldMatrix);
  59074. }
  59075. // place and scale the particle bouding sphere in the SPS local system, then update it
  59076. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59077. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59078. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59079. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59080. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59081. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59082. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59083. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59084. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59085. 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));
  59086. bSphere._update(this.mesh._worldMatrix);
  59087. }
  59088. // increment indexes for the next particle
  59089. index = idx + 3;
  59090. colorIndex = colidx + 4;
  59091. uvIndex = uvidx + 2;
  59092. }
  59093. // if the VBO must be updated
  59094. if (update) {
  59095. if (this._computeParticleColor) {
  59096. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59097. }
  59098. if (this._computeParticleTexture) {
  59099. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59100. }
  59101. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59102. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59103. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59104. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59105. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59106. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59107. for (var i = 0; i < this._normals32.length; i++) {
  59108. this._fixedNormal32[i] = this._normals32[i];
  59109. }
  59110. }
  59111. if (!this.mesh.areNormalsFrozen) {
  59112. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59113. }
  59114. }
  59115. if (this._depthSort && this._depthSortParticles) {
  59116. this.depthSortedParticles.sort(this._depthSortFunction);
  59117. var dspl = this.depthSortedParticles.length;
  59118. var sorted = 0;
  59119. var lind = 0;
  59120. var sind = 0;
  59121. var sid = 0;
  59122. for (sorted = 0; sorted < dspl; sorted++) {
  59123. lind = this.depthSortedParticles[sorted].indicesLength;
  59124. sind = this.depthSortedParticles[sorted].ind;
  59125. for (var i = 0; i < lind; i++) {
  59126. this._indices32[sid] = this._indices[sind + i];
  59127. sid++;
  59128. }
  59129. }
  59130. this.mesh.updateIndices(this._indices32);
  59131. }
  59132. }
  59133. if (this._computeBoundingBox) {
  59134. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59135. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59136. }
  59137. this.afterUpdateParticles(start, end, update);
  59138. return this;
  59139. };
  59140. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59141. this._halfroll = this._roll * 0.5;
  59142. this._halfpitch = this._pitch * 0.5;
  59143. this._halfyaw = this._yaw * 0.5;
  59144. this._sinRoll = Math.sin(this._halfroll);
  59145. this._cosRoll = Math.cos(this._halfroll);
  59146. this._sinPitch = Math.sin(this._halfpitch);
  59147. this._cosPitch = Math.cos(this._halfpitch);
  59148. this._sinYaw = Math.sin(this._halfyaw);
  59149. this._cosYaw = Math.cos(this._halfyaw);
  59150. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59151. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59152. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59153. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59154. };
  59155. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59156. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59157. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59158. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59159. this._rotMatrix.m[3] = 0;
  59160. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59161. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59162. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59163. this._rotMatrix.m[7] = 0;
  59164. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59165. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59166. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59167. this._rotMatrix.m[11] = 0;
  59168. this._rotMatrix.m[12] = 0;
  59169. this._rotMatrix.m[13] = 0;
  59170. this._rotMatrix.m[14] = 0;
  59171. this._rotMatrix.m[15] = 1.0;
  59172. };
  59173. /**
  59174. * Disposes the SPS.
  59175. */
  59176. SolidParticleSystem.prototype.dispose = function () {
  59177. this.mesh.dispose();
  59178. this.vars = null;
  59179. // drop references to internal big arrays for the GC
  59180. this._positions = null;
  59181. this._indices = null;
  59182. this._normals = null;
  59183. this._uvs = null;
  59184. this._colors = null;
  59185. this._indices32 = null;
  59186. this._positions32 = null;
  59187. this._normals32 = null;
  59188. this._fixedNormal32 = null;
  59189. this._uvs32 = null;
  59190. this._colors32 = null;
  59191. this.pickedParticles = null;
  59192. };
  59193. /**
  59194. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59195. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59196. * @returns the SPS.
  59197. */
  59198. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59199. if (!this._isVisibilityBoxLocked) {
  59200. this.mesh.refreshBoundingInfo();
  59201. }
  59202. return this;
  59203. };
  59204. /**
  59205. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59206. * @param size the size (float) of the visibility box
  59207. * note : this doesn't lock the SPS mesh bounding box.
  59208. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59209. */
  59210. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59211. var vis = size / 2;
  59212. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59213. };
  59214. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59215. /**
  59216. * Gets whether the SPS as always visible or not
  59217. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59218. */
  59219. get: function () {
  59220. return this._alwaysVisible;
  59221. },
  59222. /**
  59223. * Sets the SPS as always visible or not
  59224. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59225. */
  59226. set: function (val) {
  59227. this._alwaysVisible = val;
  59228. this.mesh.alwaysSelectAsActiveMesh = val;
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59234. /**
  59235. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59236. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59237. */
  59238. get: function () {
  59239. return this._isVisibilityBoxLocked;
  59240. },
  59241. /**
  59242. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59243. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59244. */
  59245. set: function (val) {
  59246. this._isVisibilityBoxLocked = val;
  59247. var boundingInfo = this.mesh.getBoundingInfo();
  59248. boundingInfo.isLocked = val;
  59249. },
  59250. enumerable: true,
  59251. configurable: true
  59252. });
  59253. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59254. /**
  59255. * Gets if `setParticles()` computes the particle rotations or not.
  59256. * Default value : true. The SPS is faster when it's set to false.
  59257. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59258. */
  59259. get: function () {
  59260. return this._computeParticleRotation;
  59261. },
  59262. /**
  59263. * Tells to `setParticles()` to compute the particle rotations or not.
  59264. * Default value : true. The SPS is faster when it's set to false.
  59265. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59266. */
  59267. set: function (val) {
  59268. this._computeParticleRotation = val;
  59269. },
  59270. enumerable: true,
  59271. configurable: true
  59272. });
  59273. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59274. /**
  59275. * Gets if `setParticles()` computes the particle colors or not.
  59276. * Default value : true. The SPS is faster when it's set to false.
  59277. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59278. */
  59279. get: function () {
  59280. return this._computeParticleColor;
  59281. },
  59282. /**
  59283. * Tells to `setParticles()` to compute the particle colors or not.
  59284. * Default value : true. The SPS is faster when it's set to false.
  59285. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59286. */
  59287. set: function (val) {
  59288. this._computeParticleColor = val;
  59289. },
  59290. enumerable: true,
  59291. configurable: true
  59292. });
  59293. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59294. /**
  59295. * Gets if `setParticles()` computes the particle textures or not.
  59296. * Default value : true. The SPS is faster when it's set to false.
  59297. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59298. */
  59299. get: function () {
  59300. return this._computeParticleTexture;
  59301. },
  59302. set: function (val) {
  59303. this._computeParticleTexture = val;
  59304. },
  59305. enumerable: true,
  59306. configurable: true
  59307. });
  59308. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59309. /**
  59310. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59311. * Default value : false. The SPS is faster when it's set to false.
  59312. * Note : the particle custom vertex positions aren't stored values.
  59313. */
  59314. get: function () {
  59315. return this._computeParticleVertex;
  59316. },
  59317. /**
  59318. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59319. * Default value : false. The SPS is faster when it's set to false.
  59320. * Note : the particle custom vertex positions aren't stored values.
  59321. */
  59322. set: function (val) {
  59323. this._computeParticleVertex = val;
  59324. },
  59325. enumerable: true,
  59326. configurable: true
  59327. });
  59328. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59329. /**
  59330. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59331. */
  59332. get: function () {
  59333. return this._computeBoundingBox;
  59334. },
  59335. /**
  59336. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59337. */
  59338. set: function (val) {
  59339. this._computeBoundingBox = val;
  59340. },
  59341. enumerable: true,
  59342. configurable: true
  59343. });
  59344. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59345. /**
  59346. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59347. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59348. * Default : `true`
  59349. */
  59350. get: function () {
  59351. return this._depthSortParticles;
  59352. },
  59353. /**
  59354. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59355. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59356. * Default : `true`
  59357. */
  59358. set: function (val) {
  59359. this._depthSortParticles = val;
  59360. },
  59361. enumerable: true,
  59362. configurable: true
  59363. });
  59364. // =======================================================================
  59365. // Particle behavior logic
  59366. // these following methods may be overwritten by the user to fit his needs
  59367. /**
  59368. * This function does nothing. It may be overwritten to set all the particle first values.
  59369. * The SPS doesn't call this function, you may have to call it by your own.
  59370. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59371. */
  59372. SolidParticleSystem.prototype.initParticles = function () {
  59373. };
  59374. /**
  59375. * This function does nothing. It may be overwritten to recycle a particle.
  59376. * The SPS doesn't call this function, you may have to call it by your own.
  59377. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59378. * @param particle The particle to recycle
  59379. * @returns the recycled particle
  59380. */
  59381. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59382. return particle;
  59383. };
  59384. /**
  59385. * Updates a particle : this function should be overwritten by the user.
  59386. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59387. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59388. * @example : just set a particle position or velocity and recycle conditions
  59389. * @param particle The particle to update
  59390. * @returns the updated particle
  59391. */
  59392. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59393. return particle;
  59394. };
  59395. /**
  59396. * Updates a vertex of a particle : it can be overwritten by the user.
  59397. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59398. * @param particle the current particle
  59399. * @param vertex the current index of the current particle
  59400. * @param pt the index of the current vertex in the particle shape
  59401. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59402. * @example : just set a vertex particle position
  59403. * @returns the updated vertex
  59404. */
  59405. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59406. return vertex;
  59407. };
  59408. /**
  59409. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59410. * This does nothing and may be overwritten by the user.
  59411. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59412. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59413. * @param update the boolean update value actually passed to setParticles()
  59414. */
  59415. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59416. };
  59417. /**
  59418. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59419. * This will be passed three parameters.
  59420. * This does nothing and may be overwritten by the user.
  59421. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59422. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59423. * @param update the boolean update value actually passed to setParticles()
  59424. */
  59425. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59426. };
  59427. return SolidParticleSystem;
  59428. }());
  59429. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59430. })(BABYLON || (BABYLON = {}));
  59431. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59432. var BABYLON;
  59433. (function (BABYLON) {
  59434. var ShaderMaterial = /** @class */ (function (_super) {
  59435. __extends(ShaderMaterial, _super);
  59436. function ShaderMaterial(name, scene, shaderPath, options) {
  59437. var _this = _super.call(this, name, scene) || this;
  59438. _this._textures = {};
  59439. _this._textureArrays = {};
  59440. _this._floats = {};
  59441. _this._ints = {};
  59442. _this._floatsArrays = {};
  59443. _this._colors3 = {};
  59444. _this._colors3Arrays = {};
  59445. _this._colors4 = {};
  59446. _this._vectors2 = {};
  59447. _this._vectors3 = {};
  59448. _this._vectors4 = {};
  59449. _this._matrices = {};
  59450. _this._matrices3x3 = {};
  59451. _this._matrices2x2 = {};
  59452. _this._vectors2Arrays = {};
  59453. _this._vectors3Arrays = {};
  59454. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59455. _this._shaderPath = shaderPath;
  59456. options.needAlphaBlending = options.needAlphaBlending || false;
  59457. options.needAlphaTesting = options.needAlphaTesting || false;
  59458. options.attributes = options.attributes || ["position", "normal", "uv"];
  59459. options.uniforms = options.uniforms || ["worldViewProjection"];
  59460. options.uniformBuffers = options.uniformBuffers || [];
  59461. options.samplers = options.samplers || [];
  59462. options.defines = options.defines || [];
  59463. _this._options = options;
  59464. return _this;
  59465. }
  59466. ShaderMaterial.prototype.getClassName = function () {
  59467. return "ShaderMaterial";
  59468. };
  59469. ShaderMaterial.prototype.needAlphaBlending = function () {
  59470. return this._options.needAlphaBlending;
  59471. };
  59472. ShaderMaterial.prototype.needAlphaTesting = function () {
  59473. return this._options.needAlphaTesting;
  59474. };
  59475. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59476. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59477. this._options.uniforms.push(uniformName);
  59478. }
  59479. };
  59480. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59481. if (this._options.samplers.indexOf(name) === -1) {
  59482. this._options.samplers.push(name);
  59483. }
  59484. this._textures[name] = texture;
  59485. return this;
  59486. };
  59487. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59488. if (this._options.samplers.indexOf(name) === -1) {
  59489. this._options.samplers.push(name);
  59490. }
  59491. this._checkUniform(name);
  59492. this._textureArrays[name] = textures;
  59493. return this;
  59494. };
  59495. ShaderMaterial.prototype.setFloat = function (name, value) {
  59496. this._checkUniform(name);
  59497. this._floats[name] = value;
  59498. return this;
  59499. };
  59500. ShaderMaterial.prototype.setInt = function (name, value) {
  59501. this._checkUniform(name);
  59502. this._ints[name] = value;
  59503. return this;
  59504. };
  59505. ShaderMaterial.prototype.setFloats = function (name, value) {
  59506. this._checkUniform(name);
  59507. this._floatsArrays[name] = value;
  59508. return this;
  59509. };
  59510. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59511. this._checkUniform(name);
  59512. this._colors3[name] = value;
  59513. return this;
  59514. };
  59515. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59516. this._checkUniform(name);
  59517. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59518. color.toArray(arr, arr.length);
  59519. return arr;
  59520. }, []);
  59521. return this;
  59522. };
  59523. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59524. this._checkUniform(name);
  59525. this._colors4[name] = value;
  59526. return this;
  59527. };
  59528. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59529. this._checkUniform(name);
  59530. this._vectors2[name] = value;
  59531. return this;
  59532. };
  59533. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59534. this._checkUniform(name);
  59535. this._vectors3[name] = value;
  59536. return this;
  59537. };
  59538. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59539. this._checkUniform(name);
  59540. this._vectors4[name] = value;
  59541. return this;
  59542. };
  59543. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59544. this._checkUniform(name);
  59545. this._matrices[name] = value;
  59546. return this;
  59547. };
  59548. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59549. this._checkUniform(name);
  59550. this._matrices3x3[name] = value;
  59551. return this;
  59552. };
  59553. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59554. this._checkUniform(name);
  59555. this._matrices2x2[name] = value;
  59556. return this;
  59557. };
  59558. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59559. this._checkUniform(name);
  59560. this._vectors2Arrays[name] = value;
  59561. return this;
  59562. };
  59563. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59564. this._checkUniform(name);
  59565. this._vectors3Arrays[name] = value;
  59566. return this;
  59567. };
  59568. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59569. if (!mesh) {
  59570. return true;
  59571. }
  59572. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59573. return false;
  59574. }
  59575. return false;
  59576. };
  59577. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59578. var scene = this.getScene();
  59579. var engine = scene.getEngine();
  59580. if (!this.checkReadyOnEveryCall) {
  59581. if (this._renderId === scene.getRenderId()) {
  59582. if (this._checkCache(scene, mesh, useInstances)) {
  59583. return true;
  59584. }
  59585. }
  59586. }
  59587. // Instances
  59588. var defines = [];
  59589. var attribs = [];
  59590. var fallbacks = new BABYLON.EffectFallbacks();
  59591. if (useInstances) {
  59592. defines.push("#define INSTANCES");
  59593. }
  59594. for (var index = 0; index < this._options.defines.length; index++) {
  59595. defines.push(this._options.defines[index]);
  59596. }
  59597. for (var index = 0; index < this._options.attributes.length; index++) {
  59598. attribs.push(this._options.attributes[index]);
  59599. }
  59600. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59601. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59602. defines.push("#define VERTEXCOLOR");
  59603. }
  59604. // Bones
  59605. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59606. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59607. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59608. if (mesh.numBoneInfluencers > 4) {
  59609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59611. }
  59612. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59613. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59614. fallbacks.addCPUSkinningFallback(0, mesh);
  59615. if (this._options.uniforms.indexOf("mBones") === -1) {
  59616. this._options.uniforms.push("mBones");
  59617. }
  59618. }
  59619. else {
  59620. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59621. }
  59622. // Textures
  59623. for (var name in this._textures) {
  59624. if (!this._textures[name].isReady()) {
  59625. return false;
  59626. }
  59627. }
  59628. // Alpha test
  59629. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59630. defines.push("#define ALPHATEST");
  59631. }
  59632. var previousEffect = this._effect;
  59633. var join = defines.join("\n");
  59634. this._effect = engine.createEffect(this._shaderPath, {
  59635. attributes: attribs,
  59636. uniformsNames: this._options.uniforms,
  59637. uniformBuffersNames: this._options.uniformBuffers,
  59638. samplers: this._options.samplers,
  59639. defines: join,
  59640. fallbacks: fallbacks,
  59641. onCompiled: this.onCompiled,
  59642. onError: this.onError
  59643. }, engine);
  59644. if (!this._effect.isReady()) {
  59645. return false;
  59646. }
  59647. if (previousEffect !== this._effect) {
  59648. scene.resetCachedMaterial();
  59649. }
  59650. this._renderId = scene.getRenderId();
  59651. return true;
  59652. };
  59653. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59654. var scene = this.getScene();
  59655. if (!this._effect) {
  59656. return;
  59657. }
  59658. if (this._options.uniforms.indexOf("world") !== -1) {
  59659. this._effect.setMatrix("world", world);
  59660. }
  59661. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59662. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59663. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59664. }
  59665. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59666. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59667. }
  59668. };
  59669. ShaderMaterial.prototype.bind = function (world, mesh) {
  59670. // Std values
  59671. this.bindOnlyWorldMatrix(world);
  59672. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59673. if (this._options.uniforms.indexOf("view") !== -1) {
  59674. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59675. }
  59676. if (this._options.uniforms.indexOf("projection") !== -1) {
  59677. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59678. }
  59679. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59680. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59681. }
  59682. // Bones
  59683. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59684. var name;
  59685. // Texture
  59686. for (name in this._textures) {
  59687. this._effect.setTexture(name, this._textures[name]);
  59688. }
  59689. // Texture arrays
  59690. for (name in this._textureArrays) {
  59691. this._effect.setTextureArray(name, this._textureArrays[name]);
  59692. }
  59693. // Int
  59694. for (name in this._ints) {
  59695. this._effect.setInt(name, this._ints[name]);
  59696. }
  59697. // Float
  59698. for (name in this._floats) {
  59699. this._effect.setFloat(name, this._floats[name]);
  59700. }
  59701. // Floats
  59702. for (name in this._floatsArrays) {
  59703. this._effect.setArray(name, this._floatsArrays[name]);
  59704. }
  59705. // Color3
  59706. for (name in this._colors3) {
  59707. this._effect.setColor3(name, this._colors3[name]);
  59708. }
  59709. for (name in this._colors3Arrays) {
  59710. this._effect.setArray3(name, this._colors3Arrays[name]);
  59711. }
  59712. // Color4
  59713. for (name in this._colors4) {
  59714. var color = this._colors4[name];
  59715. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59716. }
  59717. // Vector2
  59718. for (name in this._vectors2) {
  59719. this._effect.setVector2(name, this._vectors2[name]);
  59720. }
  59721. // Vector3
  59722. for (name in this._vectors3) {
  59723. this._effect.setVector3(name, this._vectors3[name]);
  59724. }
  59725. // Vector4
  59726. for (name in this._vectors4) {
  59727. this._effect.setVector4(name, this._vectors4[name]);
  59728. }
  59729. // Matrix
  59730. for (name in this._matrices) {
  59731. this._effect.setMatrix(name, this._matrices[name]);
  59732. }
  59733. // Matrix 3x3
  59734. for (name in this._matrices3x3) {
  59735. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59736. }
  59737. // Matrix 2x2
  59738. for (name in this._matrices2x2) {
  59739. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59740. }
  59741. // Vector2Array
  59742. for (name in this._vectors2Arrays) {
  59743. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59744. }
  59745. // Vector3Array
  59746. for (name in this._vectors3Arrays) {
  59747. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59748. }
  59749. }
  59750. this._afterBind(mesh);
  59751. };
  59752. ShaderMaterial.prototype.getActiveTextures = function () {
  59753. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59754. for (var name in this._textures) {
  59755. activeTextures.push(this._textures[name]);
  59756. }
  59757. for (var name in this._textureArrays) {
  59758. var array = this._textureArrays[name];
  59759. for (var index = 0; index < array.length; index++) {
  59760. activeTextures.push(array[index]);
  59761. }
  59762. }
  59763. return activeTextures;
  59764. };
  59765. ShaderMaterial.prototype.hasTexture = function (texture) {
  59766. if (_super.prototype.hasTexture.call(this, texture)) {
  59767. return true;
  59768. }
  59769. for (var name in this._textures) {
  59770. if (this._textures[name] === texture) {
  59771. return true;
  59772. }
  59773. }
  59774. for (var name in this._textureArrays) {
  59775. var array = this._textureArrays[name];
  59776. for (var index = 0; index < array.length; index++) {
  59777. if (array[index] === texture) {
  59778. return true;
  59779. }
  59780. }
  59781. }
  59782. return false;
  59783. };
  59784. ShaderMaterial.prototype.clone = function (name) {
  59785. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59786. return newShaderMaterial;
  59787. };
  59788. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59789. if (forceDisposeTextures) {
  59790. var name;
  59791. for (name in this._textures) {
  59792. this._textures[name].dispose();
  59793. }
  59794. for (name in this._textureArrays) {
  59795. var array = this._textureArrays[name];
  59796. for (var index = 0; index < array.length; index++) {
  59797. array[index].dispose();
  59798. }
  59799. }
  59800. }
  59801. this._textures = {};
  59802. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59803. };
  59804. ShaderMaterial.prototype.serialize = function () {
  59805. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59806. serializationObject.customType = "BABYLON.ShaderMaterial";
  59807. serializationObject.options = this._options;
  59808. serializationObject.shaderPath = this._shaderPath;
  59809. var name;
  59810. // Texture
  59811. serializationObject.textures = {};
  59812. for (name in this._textures) {
  59813. serializationObject.textures[name] = this._textures[name].serialize();
  59814. }
  59815. // Texture arrays
  59816. serializationObject.textureArrays = {};
  59817. for (name in this._textureArrays) {
  59818. serializationObject.textureArrays[name] = [];
  59819. var array = this._textureArrays[name];
  59820. for (var index = 0; index < array.length; index++) {
  59821. serializationObject.textureArrays[name].push(array[index].serialize());
  59822. }
  59823. }
  59824. // Float
  59825. serializationObject.floats = {};
  59826. for (name in this._floats) {
  59827. serializationObject.floats[name] = this._floats[name];
  59828. }
  59829. // Float s
  59830. serializationObject.FloatArrays = {};
  59831. for (name in this._floatsArrays) {
  59832. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59833. }
  59834. // Color3
  59835. serializationObject.colors3 = {};
  59836. for (name in this._colors3) {
  59837. serializationObject.colors3[name] = this._colors3[name].asArray();
  59838. }
  59839. // Color3 array
  59840. serializationObject.colors3Arrays = {};
  59841. for (name in this._colors3Arrays) {
  59842. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59843. }
  59844. // Color4
  59845. serializationObject.colors4 = {};
  59846. for (name in this._colors4) {
  59847. serializationObject.colors4[name] = this._colors4[name].asArray();
  59848. }
  59849. // Vector2
  59850. serializationObject.vectors2 = {};
  59851. for (name in this._vectors2) {
  59852. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59853. }
  59854. // Vector3
  59855. serializationObject.vectors3 = {};
  59856. for (name in this._vectors3) {
  59857. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59858. }
  59859. // Vector4
  59860. serializationObject.vectors4 = {};
  59861. for (name in this._vectors4) {
  59862. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59863. }
  59864. // Matrix
  59865. serializationObject.matrices = {};
  59866. for (name in this._matrices) {
  59867. serializationObject.matrices[name] = this._matrices[name].asArray();
  59868. }
  59869. // Matrix 3x3
  59870. serializationObject.matrices3x3 = {};
  59871. for (name in this._matrices3x3) {
  59872. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59873. }
  59874. // Matrix 2x2
  59875. serializationObject.matrices2x2 = {};
  59876. for (name in this._matrices2x2) {
  59877. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59878. }
  59879. // Vector2Array
  59880. serializationObject.vectors2Arrays = {};
  59881. for (name in this._vectors2Arrays) {
  59882. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59883. }
  59884. // Vector3Array
  59885. serializationObject.vectors3Arrays = {};
  59886. for (name in this._vectors3Arrays) {
  59887. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59888. }
  59889. return serializationObject;
  59890. };
  59891. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59892. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59893. var name;
  59894. // Texture
  59895. for (name in source.textures) {
  59896. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59897. }
  59898. // Texture arrays
  59899. for (name in source.textureArrays) {
  59900. var array = source.textureArrays[name];
  59901. var textureArray = new Array();
  59902. for (var index = 0; index < array.length; index++) {
  59903. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59904. }
  59905. material.setTextureArray(name, textureArray);
  59906. }
  59907. // Float
  59908. for (name in source.floats) {
  59909. material.setFloat(name, source.floats[name]);
  59910. }
  59911. // Float s
  59912. for (name in source.floatsArrays) {
  59913. material.setFloats(name, source.floatsArrays[name]);
  59914. }
  59915. // Color3
  59916. for (name in source.colors3) {
  59917. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59918. }
  59919. // Color3 arrays
  59920. for (name in source.colors3Arrays) {
  59921. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59922. if (i % 3 === 0) {
  59923. arr.push([num]);
  59924. }
  59925. else {
  59926. arr[arr.length - 1].push(num);
  59927. }
  59928. return arr;
  59929. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59930. material.setColor3Array(name, colors);
  59931. }
  59932. // Color4
  59933. for (name in source.colors4) {
  59934. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59935. }
  59936. // Vector2
  59937. for (name in source.vectors2) {
  59938. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59939. }
  59940. // Vector3
  59941. for (name in source.vectors3) {
  59942. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59943. }
  59944. // Vector4
  59945. for (name in source.vectors4) {
  59946. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59947. }
  59948. // Matrix
  59949. for (name in source.matrices) {
  59950. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59951. }
  59952. // Matrix 3x3
  59953. for (name in source.matrices3x3) {
  59954. material.setMatrix3x3(name, source.matrices3x3[name]);
  59955. }
  59956. // Matrix 2x2
  59957. for (name in source.matrices2x2) {
  59958. material.setMatrix2x2(name, source.matrices2x2[name]);
  59959. }
  59960. // Vector2Array
  59961. for (name in source.vectors2Arrays) {
  59962. material.setArray2(name, source.vectors2Arrays[name]);
  59963. }
  59964. // Vector3Array
  59965. for (name in source.vectors3Arrays) {
  59966. material.setArray3(name, source.vectors3Arrays[name]);
  59967. }
  59968. return material;
  59969. };
  59970. return ShaderMaterial;
  59971. }(BABYLON.Material));
  59972. BABYLON.ShaderMaterial = ShaderMaterial;
  59973. })(BABYLON || (BABYLON = {}));
  59974. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59975. var BABYLON;
  59976. (function (BABYLON) {
  59977. var GroundMesh = /** @class */ (function (_super) {
  59978. __extends(GroundMesh, _super);
  59979. function GroundMesh(name, scene) {
  59980. var _this = _super.call(this, name, scene) || this;
  59981. _this.generateOctree = false;
  59982. return _this;
  59983. }
  59984. GroundMesh.prototype.getClassName = function () {
  59985. return "GroundMesh";
  59986. };
  59987. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59988. get: function () {
  59989. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59990. },
  59991. enumerable: true,
  59992. configurable: true
  59993. });
  59994. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59995. get: function () {
  59996. return this._subdivisionsX;
  59997. },
  59998. enumerable: true,
  59999. configurable: true
  60000. });
  60001. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60002. get: function () {
  60003. return this._subdivisionsY;
  60004. },
  60005. enumerable: true,
  60006. configurable: true
  60007. });
  60008. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60009. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60010. this._subdivisionsX = chunksCount;
  60011. this._subdivisionsY = chunksCount;
  60012. this.subdivide(chunksCount);
  60013. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60014. };
  60015. /**
  60016. * Returns a height (y) value in the Worl system :
  60017. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60018. * Returns the ground y position if (x, z) are outside the ground surface.
  60019. */
  60020. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60021. var world = this.getWorldMatrix();
  60022. var invMat = BABYLON.Tmp.Matrix[5];
  60023. world.invertToRef(invMat);
  60024. var tmpVect = BABYLON.Tmp.Vector3[8];
  60025. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60026. x = tmpVect.x;
  60027. z = tmpVect.z;
  60028. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60029. return this.position.y;
  60030. }
  60031. if (!this._heightQuads || this._heightQuads.length == 0) {
  60032. this._initHeightQuads();
  60033. this._computeHeightQuads();
  60034. }
  60035. var facet = this._getFacetAt(x, z);
  60036. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60037. // return y in the World system
  60038. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60039. return tmpVect.y;
  60040. };
  60041. /**
  60042. * Returns a normalized vector (Vector3) orthogonal to the ground
  60043. * at the ground coordinates (x, z) expressed in the World system.
  60044. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60045. */
  60046. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60047. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60048. this.getNormalAtCoordinatesToRef(x, z, normal);
  60049. return normal;
  60050. };
  60051. /**
  60052. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60053. * at the ground coordinates (x, z) expressed in the World system.
  60054. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60055. * Returns the GroundMesh.
  60056. */
  60057. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60058. var world = this.getWorldMatrix();
  60059. var tmpMat = BABYLON.Tmp.Matrix[5];
  60060. world.invertToRef(tmpMat);
  60061. var tmpVect = BABYLON.Tmp.Vector3[8];
  60062. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60063. x = tmpVect.x;
  60064. z = tmpVect.z;
  60065. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60066. return this;
  60067. }
  60068. if (!this._heightQuads || this._heightQuads.length == 0) {
  60069. this._initHeightQuads();
  60070. this._computeHeightQuads();
  60071. }
  60072. var facet = this._getFacetAt(x, z);
  60073. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60074. return this;
  60075. };
  60076. /**
  60077. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60078. * if the ground has been updated.
  60079. * This can be used in the render loop.
  60080. * Returns the GroundMesh.
  60081. */
  60082. GroundMesh.prototype.updateCoordinateHeights = function () {
  60083. if (!this._heightQuads || this._heightQuads.length == 0) {
  60084. this._initHeightQuads();
  60085. }
  60086. this._computeHeightQuads();
  60087. return this;
  60088. };
  60089. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60090. GroundMesh.prototype._getFacetAt = function (x, z) {
  60091. // retrieve col and row from x, z coordinates in the ground local system
  60092. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60093. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60094. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60095. var facet;
  60096. if (z < quad.slope.x * x + quad.slope.y) {
  60097. facet = quad.facet1;
  60098. }
  60099. else {
  60100. facet = quad.facet2;
  60101. }
  60102. return facet;
  60103. };
  60104. // Creates and populates the heightMap array with "facet" elements :
  60105. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60106. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60107. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60108. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60109. // Returns the GroundMesh.
  60110. GroundMesh.prototype._initHeightQuads = function () {
  60111. var subdivisionsX = this._subdivisionsX;
  60112. var subdivisionsY = this._subdivisionsY;
  60113. this._heightQuads = new Array();
  60114. for (var row = 0; row < subdivisionsY; row++) {
  60115. for (var col = 0; col < subdivisionsX; col++) {
  60116. 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) };
  60117. this._heightQuads[row * subdivisionsX + col] = quad;
  60118. }
  60119. }
  60120. return this;
  60121. };
  60122. // Compute each quad element values and update the the heightMap array :
  60123. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60124. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60125. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60126. // Returns the GroundMesh.
  60127. GroundMesh.prototype._computeHeightQuads = function () {
  60128. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60129. if (!positions) {
  60130. return this;
  60131. }
  60132. var v1 = BABYLON.Tmp.Vector3[3];
  60133. var v2 = BABYLON.Tmp.Vector3[2];
  60134. var v3 = BABYLON.Tmp.Vector3[1];
  60135. var v4 = BABYLON.Tmp.Vector3[0];
  60136. var v1v2 = BABYLON.Tmp.Vector3[4];
  60137. var v1v3 = BABYLON.Tmp.Vector3[5];
  60138. var v1v4 = BABYLON.Tmp.Vector3[6];
  60139. var norm1 = BABYLON.Tmp.Vector3[7];
  60140. var norm2 = BABYLON.Tmp.Vector3[8];
  60141. var i = 0;
  60142. var j = 0;
  60143. var k = 0;
  60144. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60145. var h = 0;
  60146. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60147. var d2 = 0;
  60148. var subdivisionsX = this._subdivisionsX;
  60149. var subdivisionsY = this._subdivisionsY;
  60150. for (var row = 0; row < subdivisionsY; row++) {
  60151. for (var col = 0; col < subdivisionsX; col++) {
  60152. i = col * 3;
  60153. j = row * (subdivisionsX + 1) * 3;
  60154. k = (row + 1) * (subdivisionsX + 1) * 3;
  60155. v1.x = positions[j + i];
  60156. v1.y = positions[j + i + 1];
  60157. v1.z = positions[j + i + 2];
  60158. v2.x = positions[j + i + 3];
  60159. v2.y = positions[j + i + 4];
  60160. v2.z = positions[j + i + 5];
  60161. v3.x = positions[k + i];
  60162. v3.y = positions[k + i + 1];
  60163. v3.z = positions[k + i + 2];
  60164. v4.x = positions[k + i + 3];
  60165. v4.y = positions[k + i + 4];
  60166. v4.z = positions[k + i + 5];
  60167. // 2D slope V1V4
  60168. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60169. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60170. // facet equations :
  60171. // we compute each facet normal vector
  60172. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60173. // we compute the value d by applying the equation to v1 which belongs to the plane
  60174. // then we store the facet equation in a Vector4
  60175. v2.subtractToRef(v1, v1v2);
  60176. v3.subtractToRef(v1, v1v3);
  60177. v4.subtractToRef(v1, v1v4);
  60178. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60179. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60180. norm1.normalize();
  60181. norm2.normalize();
  60182. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60183. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60184. var quad = this._heightQuads[row * subdivisionsX + col];
  60185. quad.slope.copyFromFloats(cd, h);
  60186. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60187. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60188. }
  60189. }
  60190. return this;
  60191. };
  60192. GroundMesh.prototype.serialize = function (serializationObject) {
  60193. _super.prototype.serialize.call(this, serializationObject);
  60194. serializationObject.subdivisionsX = this._subdivisionsX;
  60195. serializationObject.subdivisionsY = this._subdivisionsY;
  60196. serializationObject.minX = this._minX;
  60197. serializationObject.maxX = this._maxX;
  60198. serializationObject.minZ = this._minZ;
  60199. serializationObject.maxZ = this._maxZ;
  60200. serializationObject.width = this._width;
  60201. serializationObject.height = this._height;
  60202. };
  60203. GroundMesh.Parse = function (parsedMesh, scene) {
  60204. var result = new GroundMesh(parsedMesh.name, scene);
  60205. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60206. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60207. result._minX = parsedMesh.minX;
  60208. result._maxX = parsedMesh.maxX;
  60209. result._minZ = parsedMesh.minZ;
  60210. result._maxZ = parsedMesh.maxZ;
  60211. result._width = parsedMesh.width;
  60212. result._height = parsedMesh.height;
  60213. return result;
  60214. };
  60215. return GroundMesh;
  60216. }(BABYLON.Mesh));
  60217. BABYLON.GroundMesh = GroundMesh;
  60218. })(BABYLON || (BABYLON = {}));
  60219. //# sourceMappingURL=babylon.groundMesh.js.map
  60220. var BABYLON;
  60221. (function (BABYLON) {
  60222. /**
  60223. * Creates an instance based on a source mesh.
  60224. */
  60225. var InstancedMesh = /** @class */ (function (_super) {
  60226. __extends(InstancedMesh, _super);
  60227. function InstancedMesh(name, source) {
  60228. var _this = _super.call(this, name, source.getScene()) || this;
  60229. source.instances.push(_this);
  60230. _this._sourceMesh = source;
  60231. _this.position.copyFrom(source.position);
  60232. _this.rotation.copyFrom(source.rotation);
  60233. _this.scaling.copyFrom(source.scaling);
  60234. if (source.rotationQuaternion) {
  60235. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60236. }
  60237. _this.infiniteDistance = source.infiniteDistance;
  60238. _this.setPivotMatrix(source.getPivotMatrix());
  60239. _this.refreshBoundingInfo();
  60240. _this._syncSubMeshes();
  60241. return _this;
  60242. }
  60243. /**
  60244. * Returns the string "InstancedMesh".
  60245. */
  60246. InstancedMesh.prototype.getClassName = function () {
  60247. return "InstancedMesh";
  60248. };
  60249. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60250. // Methods
  60251. get: function () {
  60252. return this._sourceMesh.receiveShadows;
  60253. },
  60254. enumerable: true,
  60255. configurable: true
  60256. });
  60257. Object.defineProperty(InstancedMesh.prototype, "material", {
  60258. get: function () {
  60259. return this._sourceMesh.material;
  60260. },
  60261. enumerable: true,
  60262. configurable: true
  60263. });
  60264. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60265. get: function () {
  60266. return this._sourceMesh.visibility;
  60267. },
  60268. enumerable: true,
  60269. configurable: true
  60270. });
  60271. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60272. get: function () {
  60273. return this._sourceMesh.skeleton;
  60274. },
  60275. enumerable: true,
  60276. configurable: true
  60277. });
  60278. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60279. get: function () {
  60280. return this._sourceMesh.renderingGroupId;
  60281. },
  60282. set: function (value) {
  60283. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60284. return;
  60285. }
  60286. //no-op with warning
  60287. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60288. },
  60289. enumerable: true,
  60290. configurable: true
  60291. });
  60292. /**
  60293. * Returns the total number of vertices (integer).
  60294. */
  60295. InstancedMesh.prototype.getTotalVertices = function () {
  60296. return this._sourceMesh.getTotalVertices();
  60297. };
  60298. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60299. get: function () {
  60300. return this._sourceMesh;
  60301. },
  60302. enumerable: true,
  60303. configurable: true
  60304. });
  60305. /**
  60306. * Is this node ready to be used/rendered
  60307. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60308. * @return {boolean} is it ready
  60309. */
  60310. InstancedMesh.prototype.isReady = function (completeCheck) {
  60311. if (completeCheck === void 0) { completeCheck = false; }
  60312. return this._sourceMesh.isReady(completeCheck, true);
  60313. };
  60314. /**
  60315. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60316. */
  60317. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60318. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60319. };
  60320. /**
  60321. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60322. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60323. * The `data` are either a numeric array either a Float32Array.
  60324. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60325. * 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).
  60326. * Note that a new underlying VertexBuffer object is created each call.
  60327. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60328. *
  60329. * Possible `kind` values :
  60330. * - BABYLON.VertexBuffer.PositionKind
  60331. * - BABYLON.VertexBuffer.UVKind
  60332. * - BABYLON.VertexBuffer.UV2Kind
  60333. * - BABYLON.VertexBuffer.UV3Kind
  60334. * - BABYLON.VertexBuffer.UV4Kind
  60335. * - BABYLON.VertexBuffer.UV5Kind
  60336. * - BABYLON.VertexBuffer.UV6Kind
  60337. * - BABYLON.VertexBuffer.ColorKind
  60338. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60339. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60340. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60341. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60342. *
  60343. * Returns the Mesh.
  60344. */
  60345. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60346. if (this.sourceMesh) {
  60347. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60348. }
  60349. return this.sourceMesh;
  60350. };
  60351. /**
  60352. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60353. * If the mesh has no geometry, it is simply returned as it is.
  60354. * The `data` are either a numeric array either a Float32Array.
  60355. * No new underlying VertexBuffer object is created.
  60356. * 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.
  60357. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60358. *
  60359. * Possible `kind` values :
  60360. * - BABYLON.VertexBuffer.PositionKind
  60361. * - BABYLON.VertexBuffer.UVKind
  60362. * - BABYLON.VertexBuffer.UV2Kind
  60363. * - BABYLON.VertexBuffer.UV3Kind
  60364. * - BABYLON.VertexBuffer.UV4Kind
  60365. * - BABYLON.VertexBuffer.UV5Kind
  60366. * - BABYLON.VertexBuffer.UV6Kind
  60367. * - BABYLON.VertexBuffer.ColorKind
  60368. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60369. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60370. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60371. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60372. *
  60373. * Returns the Mesh.
  60374. */
  60375. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60376. if (this.sourceMesh) {
  60377. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60378. }
  60379. return this.sourceMesh;
  60380. };
  60381. /**
  60382. * Sets the mesh indices.
  60383. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60384. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60385. * This method creates a new index buffer each call.
  60386. * Returns the Mesh.
  60387. */
  60388. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60389. if (totalVertices === void 0) { totalVertices = null; }
  60390. if (this.sourceMesh) {
  60391. this.sourceMesh.setIndices(indices, totalVertices);
  60392. }
  60393. return this.sourceMesh;
  60394. };
  60395. /**
  60396. * Boolean : True if the mesh owns the requested kind of data.
  60397. */
  60398. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60399. return this._sourceMesh.isVerticesDataPresent(kind);
  60400. };
  60401. /**
  60402. * Returns an array of indices (IndicesArray).
  60403. */
  60404. InstancedMesh.prototype.getIndices = function () {
  60405. return this._sourceMesh.getIndices();
  60406. };
  60407. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60408. get: function () {
  60409. return this._sourceMesh._positions;
  60410. },
  60411. enumerable: true,
  60412. configurable: true
  60413. });
  60414. /**
  60415. * Sets a new updated BoundingInfo to the mesh.
  60416. * Returns the mesh.
  60417. */
  60418. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60419. var meshBB = this._sourceMesh.getBoundingInfo();
  60420. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60421. this._updateBoundingInfo();
  60422. return this;
  60423. };
  60424. InstancedMesh.prototype._preActivate = function () {
  60425. if (this._currentLOD) {
  60426. this._currentLOD._preActivate();
  60427. }
  60428. return this;
  60429. };
  60430. InstancedMesh.prototype._activate = function (renderId) {
  60431. if (this._currentLOD) {
  60432. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60433. }
  60434. return this;
  60435. };
  60436. /**
  60437. * Returns the current associated LOD AbstractMesh.
  60438. */
  60439. InstancedMesh.prototype.getLOD = function (camera) {
  60440. if (!camera) {
  60441. return this;
  60442. }
  60443. var boundingInfo = this.getBoundingInfo();
  60444. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60445. if (this._currentLOD === this.sourceMesh) {
  60446. return this;
  60447. }
  60448. return this._currentLOD;
  60449. };
  60450. InstancedMesh.prototype._syncSubMeshes = function () {
  60451. this.releaseSubMeshes();
  60452. if (this._sourceMesh.subMeshes) {
  60453. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60454. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60455. }
  60456. }
  60457. return this;
  60458. };
  60459. InstancedMesh.prototype._generatePointsArray = function () {
  60460. return this._sourceMesh._generatePointsArray();
  60461. };
  60462. /**
  60463. * Creates a new InstancedMesh from the current mesh.
  60464. * - name (string) : the cloned mesh name
  60465. * - newParent (optional Node) : the optional Node to parent the clone to.
  60466. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60467. *
  60468. * Returns the clone.
  60469. */
  60470. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60471. var result = this._sourceMesh.createInstance(name);
  60472. // Deep copy
  60473. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60474. // Bounding info
  60475. this.refreshBoundingInfo();
  60476. // Parent
  60477. if (newParent) {
  60478. result.parent = newParent;
  60479. }
  60480. if (!doNotCloneChildren) {
  60481. // Children
  60482. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60483. var mesh = this.getScene().meshes[index];
  60484. if (mesh.parent === this) {
  60485. mesh.clone(mesh.name, result);
  60486. }
  60487. }
  60488. }
  60489. result.computeWorldMatrix(true);
  60490. return result;
  60491. };
  60492. /**
  60493. * Disposes the InstancedMesh.
  60494. * Returns nothing.
  60495. */
  60496. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60497. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60498. // Remove from mesh
  60499. var index = this._sourceMesh.instances.indexOf(this);
  60500. this._sourceMesh.instances.splice(index, 1);
  60501. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60502. };
  60503. return InstancedMesh;
  60504. }(BABYLON.AbstractMesh));
  60505. BABYLON.InstancedMesh = InstancedMesh;
  60506. })(BABYLON || (BABYLON = {}));
  60507. //# sourceMappingURL=babylon.instancedMesh.js.map
  60508. var BABYLON;
  60509. (function (BABYLON) {
  60510. var LinesMesh = /** @class */ (function (_super) {
  60511. __extends(LinesMesh, _super);
  60512. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60513. if (scene === void 0) { scene = null; }
  60514. if (parent === void 0) { parent = null; }
  60515. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60516. _this.useVertexColor = useVertexColor;
  60517. _this.useVertexAlpha = useVertexAlpha;
  60518. _this.color = new BABYLON.Color3(1, 1, 1);
  60519. _this.alpha = 1;
  60520. if (source) {
  60521. _this.color = source.color.clone();
  60522. _this.alpha = source.alpha;
  60523. _this.useVertexColor = source.useVertexColor;
  60524. _this.useVertexAlpha = source.useVertexAlpha;
  60525. }
  60526. _this._intersectionThreshold = 0.1;
  60527. var defines = [];
  60528. var options = {
  60529. attributes: [BABYLON.VertexBuffer.PositionKind],
  60530. uniforms: ["world", "viewProjection"],
  60531. needAlphaBlending: true,
  60532. defines: defines
  60533. };
  60534. if (useVertexAlpha === false) {
  60535. options.needAlphaBlending = false;
  60536. }
  60537. if (!useVertexColor) {
  60538. options.uniforms.push("color");
  60539. }
  60540. else {
  60541. options.defines.push("#define VERTEXCOLOR");
  60542. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60543. }
  60544. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60545. return _this;
  60546. }
  60547. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60548. /**
  60549. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60550. * This margin is expressed in world space coordinates, so its value may vary.
  60551. * Default value is 0.1
  60552. * @returns the intersection Threshold value.
  60553. */
  60554. get: function () {
  60555. return this._intersectionThreshold;
  60556. },
  60557. /**
  60558. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60559. * This margin is expressed in world space coordinates, so its value may vary.
  60560. * @param value the new threshold to apply
  60561. */
  60562. set: function (value) {
  60563. if (this._intersectionThreshold === value) {
  60564. return;
  60565. }
  60566. this._intersectionThreshold = value;
  60567. if (this.geometry) {
  60568. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60569. }
  60570. },
  60571. enumerable: true,
  60572. configurable: true
  60573. });
  60574. /**
  60575. * Returns the string "LineMesh"
  60576. */
  60577. LinesMesh.prototype.getClassName = function () {
  60578. return "LinesMesh";
  60579. };
  60580. Object.defineProperty(LinesMesh.prototype, "material", {
  60581. get: function () {
  60582. return this._colorShader;
  60583. },
  60584. set: function (value) {
  60585. // Do nothing
  60586. },
  60587. enumerable: true,
  60588. configurable: true
  60589. });
  60590. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60591. get: function () {
  60592. return false;
  60593. },
  60594. enumerable: true,
  60595. configurable: true
  60596. });
  60597. LinesMesh.prototype.createInstance = function (name) {
  60598. throw new Error("LinesMeshes do not support createInstance.");
  60599. };
  60600. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60601. if (!this._geometry) {
  60602. return this;
  60603. }
  60604. // VBOs
  60605. this._geometry._bind(this._colorShader.getEffect());
  60606. // Color
  60607. if (!this.useVertexColor) {
  60608. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60609. }
  60610. return this;
  60611. };
  60612. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60613. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60614. return this;
  60615. }
  60616. var engine = this.getScene().getEngine();
  60617. // Draw order
  60618. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60619. return this;
  60620. };
  60621. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60622. this._colorShader.dispose();
  60623. _super.prototype.dispose.call(this, doNotRecurse);
  60624. };
  60625. /**
  60626. * Returns a new LineMesh object cloned from the current one.
  60627. */
  60628. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60629. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60630. };
  60631. return LinesMesh;
  60632. }(BABYLON.Mesh));
  60633. BABYLON.LinesMesh = LinesMesh;
  60634. })(BABYLON || (BABYLON = {}));
  60635. //# sourceMappingURL=babylon.linesMesh.js.map
  60636. var BABYLON;
  60637. (function (BABYLON) {
  60638. /**
  60639. * Class containing static functions to help procedurally build meshes
  60640. */
  60641. var MeshBuilder = /** @class */ (function () {
  60642. function MeshBuilder() {
  60643. }
  60644. MeshBuilder.updateSideOrientation = function (orientation) {
  60645. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60646. return BABYLON.Mesh.DOUBLESIDE;
  60647. }
  60648. if (orientation === undefined || orientation === null) {
  60649. return BABYLON.Mesh.FRONTSIDE;
  60650. }
  60651. return orientation;
  60652. };
  60653. /**
  60654. * Creates a box mesh
  60655. * * The parameter `size` sets the size (float) of each box side (default 1)
  60656. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60657. * * 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)
  60658. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60659. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60660. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60661. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60662. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60663. * @param name defines the name of the mesh
  60664. * @param options defines the options used to create the mesh
  60665. * @param scene defines the hosting scene
  60666. * @returns the box mesh
  60667. */
  60668. MeshBuilder.CreateBox = function (name, options, scene) {
  60669. if (scene === void 0) { scene = null; }
  60670. var box = new BABYLON.Mesh(name, scene);
  60671. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60672. box._originalBuilderSideOrientation = options.sideOrientation;
  60673. var vertexData = BABYLON.VertexData.CreateBox(options);
  60674. vertexData.applyToMesh(box, options.updatable);
  60675. return box;
  60676. };
  60677. /**
  60678. * Creates a sphere mesh
  60679. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60680. * * 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`)
  60681. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60682. * * 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
  60683. * * 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)
  60684. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60685. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60686. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60687. * @param name defines the name of the mesh
  60688. * @param options defines the options used to create the mesh
  60689. * @param scene defines the hosting scene
  60690. * @returns the sphere mesh
  60691. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60692. */
  60693. MeshBuilder.CreateSphere = function (name, options, scene) {
  60694. var sphere = new BABYLON.Mesh(name, scene);
  60695. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60696. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60697. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60698. vertexData.applyToMesh(sphere, options.updatable);
  60699. return sphere;
  60700. };
  60701. /**
  60702. * Creates a plane polygonal mesh. By default, this is a disc
  60703. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60704. * * 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
  60705. * * 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
  60706. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60707. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60708. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60709. * @param name defines the name of the mesh
  60710. * @param options defines the options used to create the mesh
  60711. * @param scene defines the hosting scene
  60712. * @returns the plane polygonal mesh
  60713. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60714. */
  60715. MeshBuilder.CreateDisc = function (name, options, scene) {
  60716. if (scene === void 0) { scene = null; }
  60717. var disc = new BABYLON.Mesh(name, scene);
  60718. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60719. disc._originalBuilderSideOrientation = options.sideOrientation;
  60720. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60721. vertexData.applyToMesh(disc, options.updatable);
  60722. return disc;
  60723. };
  60724. /**
  60725. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60726. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60727. * * 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`)
  60728. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60729. * * 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
  60730. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60731. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60732. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60733. * @param name defines the name of the mesh
  60734. * @param options defines the options used to create the mesh
  60735. * @param scene defines the hosting scene
  60736. * @returns the icosahedron mesh
  60737. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60738. */
  60739. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60740. var sphere = new BABYLON.Mesh(name, scene);
  60741. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60742. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60743. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60744. vertexData.applyToMesh(sphere, options.updatable);
  60745. return sphere;
  60746. };
  60747. ;
  60748. /**
  60749. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60750. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60751. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60752. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60753. * * 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
  60754. * * 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
  60755. * * 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
  60756. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60757. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60758. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60759. * * 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
  60760. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60761. * * 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 if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60762. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60763. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60764. * @param name defines the name of the mesh
  60765. * @param options defines the options used to create the mesh
  60766. * @param scene defines the hosting scene
  60767. * @returns the ribbon mesh
  60768. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60769. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60770. */
  60771. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60772. if (scene === void 0) { scene = null; }
  60773. var pathArray = options.pathArray;
  60774. var closeArray = options.closeArray;
  60775. var closePath = options.closePath;
  60776. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60777. var instance = options.instance;
  60778. var updatable = options.updatable;
  60779. if (instance) { // existing ribbon instance update
  60780. // positionFunction : ribbon case
  60781. // only pathArray and sideOrientation parameters are taken into account for positions update
  60782. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60783. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60784. var positionFunction = function (positions) {
  60785. var minlg = pathArray[0].length;
  60786. var i = 0;
  60787. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60788. for (var si = 1; si <= ns; si++) {
  60789. for (var p = 0; p < pathArray.length; p++) {
  60790. var path = pathArray[p];
  60791. var l = path.length;
  60792. minlg = (minlg < l) ? minlg : l;
  60793. var j = 0;
  60794. while (j < minlg) {
  60795. positions[i] = path[j].x;
  60796. positions[i + 1] = path[j].y;
  60797. positions[i + 2] = path[j].z;
  60798. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60799. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60800. }
  60801. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60802. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60803. }
  60804. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60805. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60806. }
  60807. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60808. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60809. }
  60810. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60811. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60812. }
  60813. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60814. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60815. }
  60816. j++;
  60817. i += 3;
  60818. }
  60819. if (instance._closePath) {
  60820. positions[i] = path[0].x;
  60821. positions[i + 1] = path[0].y;
  60822. positions[i + 2] = path[0].z;
  60823. i += 3;
  60824. }
  60825. }
  60826. }
  60827. };
  60828. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60829. positionFunction(positions);
  60830. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60831. instance._boundingInfo.update(instance._worldMatrix);
  60832. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60833. if (options.colors) {
  60834. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60835. for (var c = 0; c < options.colors.length; c++) {
  60836. colors[c * 4] = options.colors[c].r;
  60837. colors[c * 4 + 1] = options.colors[c].g;
  60838. colors[c * 4 + 2] = options.colors[c].b;
  60839. colors[c * 4 + 3] = options.colors[c].a;
  60840. }
  60841. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60842. }
  60843. if (options.uvs) {
  60844. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60845. for (var i = 0; i < options.uvs.length; i++) {
  60846. uvs[i * 2] = options.uvs[i].x;
  60847. uvs[i * 2 + 1] = options.uvs[i].y;
  60848. }
  60849. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60850. }
  60851. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60852. var indices = instance.getIndices();
  60853. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60854. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60855. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60856. if (instance._closePath) {
  60857. var indexFirst = 0;
  60858. var indexLast = 0;
  60859. for (var p = 0; p < pathArray.length; p++) {
  60860. indexFirst = instance._idx[p] * 3;
  60861. if (p + 1 < pathArray.length) {
  60862. indexLast = (instance._idx[p + 1] - 1) * 3;
  60863. }
  60864. else {
  60865. indexLast = normals.length - 3;
  60866. }
  60867. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60868. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60869. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60870. normals[indexLast] = normals[indexFirst];
  60871. normals[indexLast + 1] = normals[indexFirst + 1];
  60872. normals[indexLast + 2] = normals[indexFirst + 2];
  60873. }
  60874. }
  60875. if (!(instance.areNormalsFrozen)) {
  60876. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60877. }
  60878. }
  60879. return instance;
  60880. }
  60881. else { // new ribbon creation
  60882. var ribbon = new BABYLON.Mesh(name, scene);
  60883. ribbon._originalBuilderSideOrientation = sideOrientation;
  60884. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60885. if (closePath) {
  60886. ribbon._idx = vertexData._idx;
  60887. }
  60888. ribbon._closePath = closePath;
  60889. ribbon._closeArray = closeArray;
  60890. vertexData.applyToMesh(ribbon, updatable);
  60891. return ribbon;
  60892. }
  60893. };
  60894. /**
  60895. * Creates a cylinder or a cone mesh
  60896. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60897. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60898. * * 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.
  60899. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60900. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60901. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60902. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60903. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60904. * * 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).
  60905. * * 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
  60906. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60907. * * 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
  60908. * * 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.
  60909. * * If `enclose` is false, a ring surface is one element.
  60910. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60911. * * 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
  60912. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60913. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60914. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60915. * @param name defines the name of the mesh
  60916. * @param options defines the options used to create the mesh
  60917. * @param scene defines the hosting scene
  60918. * @returns the cylinder mesh
  60919. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60920. */
  60921. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60922. var cylinder = new BABYLON.Mesh(name, scene);
  60923. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60924. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60925. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60926. vertexData.applyToMesh(cylinder, options.updatable);
  60927. return cylinder;
  60928. };
  60929. /**
  60930. * Creates a torus mesh
  60931. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60932. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60933. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60934. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60935. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60936. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60937. * @param name defines the name of the mesh
  60938. * @param options defines the options used to create the mesh
  60939. * @param scene defines the hosting scene
  60940. * @returns the torus mesh
  60941. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60942. */
  60943. MeshBuilder.CreateTorus = function (name, options, scene) {
  60944. var torus = new BABYLON.Mesh(name, scene);
  60945. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60946. torus._originalBuilderSideOrientation = options.sideOrientation;
  60947. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60948. vertexData.applyToMesh(torus, options.updatable);
  60949. return torus;
  60950. };
  60951. /**
  60952. * Creates a torus knot mesh
  60953. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60954. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60955. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60956. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60957. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60958. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60959. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60960. * @param name defines the name of the mesh
  60961. * @param options defines the options used to create the mesh
  60962. * @param scene defines the hosting scene
  60963. * @returns the torus knot mesh
  60964. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60965. */
  60966. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60967. var torusKnot = new BABYLON.Mesh(name, scene);
  60968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60969. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60970. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60971. vertexData.applyToMesh(torusKnot, options.updatable);
  60972. return torusKnot;
  60973. };
  60974. /**
  60975. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60976. * * 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
  60977. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60978. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60979. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60980. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60981. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60982. * * 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
  60983. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60984. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60985. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60986. * @param name defines the name of the new line system
  60987. * @param options defines the options used to create the line system
  60988. * @param scene defines the hosting scene
  60989. * @returns a new line system mesh
  60990. */
  60991. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60992. var instance = options.instance;
  60993. var lines = options.lines;
  60994. var colors = options.colors;
  60995. if (instance) { // lines update
  60996. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60997. var vertexColor;
  60998. var lineColors;
  60999. if (colors) {
  61000. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61001. }
  61002. var i = 0;
  61003. var c = 0;
  61004. for (var l = 0; l < lines.length; l++) {
  61005. var points = lines[l];
  61006. for (var p = 0; p < points.length; p++) {
  61007. positions[i] = points[p].x;
  61008. positions[i + 1] = points[p].y;
  61009. positions[i + 2] = points[p].z;
  61010. if (colors && vertexColor) {
  61011. lineColors = colors[l];
  61012. vertexColor[c] = lineColors[p].r;
  61013. vertexColor[c + 1] = lineColors[p].g;
  61014. vertexColor[c + 2] = lineColors[p].b;
  61015. vertexColor[c + 3] = lineColors[p].a;
  61016. c += 4;
  61017. }
  61018. i += 3;
  61019. }
  61020. }
  61021. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61022. if (colors && vertexColor) {
  61023. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61024. }
  61025. return instance;
  61026. }
  61027. // line system creation
  61028. var useVertexColor = (colors) ? true : false;
  61029. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61030. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61031. vertexData.applyToMesh(lineSystem, options.updatable);
  61032. return lineSystem;
  61033. };
  61034. /**
  61035. * Creates a line mesh
  61036. * 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
  61037. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61038. * * The parameter `points` is an array successive Vector3
  61039. * * 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
  61040. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61041. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61042. * * When updating an instance, remember that only point positions can change, not the number of points
  61043. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61044. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61045. * @param name defines the name of the new line system
  61046. * @param options defines the options used to create the line system
  61047. * @param scene defines the hosting scene
  61048. * @returns a new line mesh
  61049. */
  61050. MeshBuilder.CreateLines = function (name, options, scene) {
  61051. if (scene === void 0) { scene = null; }
  61052. var colors = (options.colors) ? [options.colors] : null;
  61053. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61054. return lines;
  61055. };
  61056. /**
  61057. * Creates a dashed line mesh
  61058. * * 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
  61059. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61060. * * The parameter `points` is an array successive Vector3
  61061. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61062. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61063. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61064. * * 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
  61065. * * When updating an instance, remember that only point positions can change, not the number of points
  61066. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61067. * @param name defines the name of the mesh
  61068. * @param options defines the options used to create the mesh
  61069. * @param scene defines the hosting scene
  61070. * @returns the dashed line mesh
  61071. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61072. */
  61073. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61074. if (scene === void 0) { scene = null; }
  61075. var points = options.points;
  61076. var instance = options.instance;
  61077. var gapSize = options.gapSize || 1;
  61078. var dashSize = options.dashSize || 3;
  61079. if (instance) { // dashed lines update
  61080. var positionFunction = function (positions) {
  61081. var curvect = BABYLON.Vector3.Zero();
  61082. var nbSeg = positions.length / 6;
  61083. var lg = 0;
  61084. var nb = 0;
  61085. var shft = 0;
  61086. var dashshft = 0;
  61087. var curshft = 0;
  61088. var p = 0;
  61089. var i = 0;
  61090. var j = 0;
  61091. for (i = 0; i < points.length - 1; i++) {
  61092. points[i + 1].subtractToRef(points[i], curvect);
  61093. lg += curvect.length();
  61094. }
  61095. shft = lg / nbSeg;
  61096. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61097. for (i = 0; i < points.length - 1; i++) {
  61098. points[i + 1].subtractToRef(points[i], curvect);
  61099. nb = Math.floor(curvect.length() / shft);
  61100. curvect.normalize();
  61101. j = 0;
  61102. while (j < nb && p < positions.length) {
  61103. curshft = shft * j;
  61104. positions[p] = points[i].x + curshft * curvect.x;
  61105. positions[p + 1] = points[i].y + curshft * curvect.y;
  61106. positions[p + 2] = points[i].z + curshft * curvect.z;
  61107. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61108. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61109. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61110. p += 6;
  61111. j++;
  61112. }
  61113. }
  61114. while (p < positions.length) {
  61115. positions[p] = points[i].x;
  61116. positions[p + 1] = points[i].y;
  61117. positions[p + 2] = points[i].z;
  61118. p += 3;
  61119. }
  61120. };
  61121. instance.updateMeshPositions(positionFunction, false);
  61122. return instance;
  61123. }
  61124. // dashed lines creation
  61125. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61126. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61127. vertexData.applyToMesh(dashedLines, options.updatable);
  61128. dashedLines.dashSize = dashSize;
  61129. dashedLines.gapSize = gapSize;
  61130. return dashedLines;
  61131. };
  61132. /**
  61133. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61134. * * 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 extruded along the Z axis.
  61135. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61136. * * 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.
  61137. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61138. * * 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
  61139. * * 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
  61140. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61141. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61142. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61143. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61144. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61145. * @param name defines the name of the mesh
  61146. * @param options defines the options used to create the mesh
  61147. * @param scene defines the hosting scene
  61148. * @returns the extruded shape mesh
  61149. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61150. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61151. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61152. */
  61153. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61154. if (scene === void 0) { scene = null; }
  61155. var path = options.path;
  61156. var shape = options.shape;
  61157. var scale = options.scale || 1;
  61158. var rotation = options.rotation || 0;
  61159. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61160. var updatable = options.updatable;
  61161. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61162. var instance = options.instance || null;
  61163. var invertUV = options.invertUV || false;
  61164. 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);
  61165. };
  61166. /**
  61167. * Creates an custom extruded shape mesh.
  61168. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61169. * * 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 extruded along the Z axis.
  61170. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61171. * * 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 and the distance of this point from the begining of the path
  61172. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61173. * * 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 and the distance of this point from the begining of the path
  61174. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61175. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61176. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61177. * * 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
  61178. * * 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
  61179. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61180. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61181. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61182. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61184. * @param name defines the name of the mesh
  61185. * @param options defines the options used to create the mesh
  61186. * @param scene defines the hosting scene
  61187. * @returns the custom extruded shape mesh
  61188. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61189. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61190. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61191. */
  61192. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61193. var path = options.path;
  61194. var shape = options.shape;
  61195. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61196. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61197. var ribbonCloseArray = options.ribbonCloseArray || false;
  61198. var ribbonClosePath = options.ribbonClosePath || false;
  61199. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61200. var updatable = options.updatable;
  61201. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61202. var instance = options.instance;
  61203. var invertUV = options.invertUV || false;
  61204. 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);
  61205. };
  61206. /**
  61207. * Creates lathe mesh.
  61208. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61209. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61210. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61211. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61212. * * 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
  61213. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61214. * * 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
  61215. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61216. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61217. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61218. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61219. * @param name defines the name of the mesh
  61220. * @param options defines the options used to create the mesh
  61221. * @param scene defines the hosting scene
  61222. * @returns the lathe mesh
  61223. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61224. */
  61225. MeshBuilder.CreateLathe = function (name, options, scene) {
  61226. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61227. var closed = (options.closed === undefined) ? true : options.closed;
  61228. var shape = options.shape;
  61229. var radius = options.radius || 1;
  61230. var tessellation = options.tessellation || 64;
  61231. var updatable = options.updatable;
  61232. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61233. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61234. var pi2 = Math.PI * 2;
  61235. var paths = new Array();
  61236. var invertUV = options.invertUV || false;
  61237. var i = 0;
  61238. var p = 0;
  61239. var step = pi2 / tessellation * arc;
  61240. var rotated;
  61241. var path = new Array();
  61242. for (i = 0; i <= tessellation; i++) {
  61243. var path = [];
  61244. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61245. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61246. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61247. }
  61248. for (p = 0; p < shape.length; p++) {
  61249. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61250. path.push(rotated);
  61251. }
  61252. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61253. 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));
  61254. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61255. }
  61256. paths.push(path);
  61257. }
  61258. // lathe ribbon
  61259. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61260. return lathe;
  61261. };
  61262. /**
  61263. * Creates a plane mesh
  61264. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61265. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61266. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61267. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61268. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61270. * @param name defines the name of the mesh
  61271. * @param options defines the options used to create the mesh
  61272. * @param scene defines the hosting scene
  61273. * @returns the plane mesh
  61274. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61275. */
  61276. MeshBuilder.CreatePlane = function (name, options, scene) {
  61277. var plane = new BABYLON.Mesh(name, scene);
  61278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61279. plane._originalBuilderSideOrientation = options.sideOrientation;
  61280. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61281. vertexData.applyToMesh(plane, options.updatable);
  61282. if (options.sourcePlane) {
  61283. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61284. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61285. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61286. plane.rotate(vectorProduct, product);
  61287. }
  61288. return plane;
  61289. };
  61290. /**
  61291. * Creates a ground mesh
  61292. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61293. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61294. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61295. * @param name defines the name of the mesh
  61296. * @param options defines the options used to create the mesh
  61297. * @param scene defines the hosting scene
  61298. * @returns the ground mesh
  61299. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61300. */
  61301. MeshBuilder.CreateGround = function (name, options, scene) {
  61302. var ground = new BABYLON.GroundMesh(name, scene);
  61303. ground._setReady(false);
  61304. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61305. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61306. ground._width = options.width || 1;
  61307. ground._height = options.height || 1;
  61308. ground._maxX = ground._width / 2;
  61309. ground._maxZ = ground._height / 2;
  61310. ground._minX = -ground._maxX;
  61311. ground._minZ = -ground._maxZ;
  61312. var vertexData = BABYLON.VertexData.CreateGround(options);
  61313. vertexData.applyToMesh(ground, options.updatable);
  61314. ground._setReady(true);
  61315. return ground;
  61316. };
  61317. /**
  61318. * Creates a tiled ground mesh
  61319. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61320. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61321. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61322. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61323. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61324. * @param name defines the name of the mesh
  61325. * @param options defines the options used to create the mesh
  61326. * @param scene defines the hosting scene
  61327. * @returns the tiled ground mesh
  61328. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61329. */
  61330. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61331. var tiledGround = new BABYLON.Mesh(name, scene);
  61332. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61333. vertexData.applyToMesh(tiledGround, options.updatable);
  61334. return tiledGround;
  61335. };
  61336. /**
  61337. * Creates a ground mesh from a height map
  61338. * * The parameter `url` sets the URL of the height map image resource.
  61339. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61340. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61341. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61342. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61343. * * 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.
  61344. * * 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).
  61345. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61346. * @param name defines the name of the mesh
  61347. * @param url defines the url to the height map
  61348. * @param options defines the options used to create the mesh
  61349. * @param scene defines the hosting scene
  61350. * @returns the ground mesh
  61351. * @see http://doc.babylonjs.com/babylon101/height_map
  61352. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61353. */
  61354. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61355. var width = options.width || 10.0;
  61356. var height = options.height || 10.0;
  61357. var subdivisions = options.subdivisions || 1 | 0;
  61358. var minHeight = options.minHeight || 0.0;
  61359. var maxHeight = options.maxHeight || 1.0;
  61360. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61361. var updatable = options.updatable;
  61362. var onReady = options.onReady;
  61363. var ground = new BABYLON.GroundMesh(name, scene);
  61364. ground._subdivisionsX = subdivisions;
  61365. ground._subdivisionsY = subdivisions;
  61366. ground._width = width;
  61367. ground._height = height;
  61368. ground._maxX = ground._width / 2.0;
  61369. ground._maxZ = ground._height / 2.0;
  61370. ground._minX = -ground._maxX;
  61371. ground._minZ = -ground._maxZ;
  61372. ground._setReady(false);
  61373. var onload = function (img) {
  61374. // Getting height map data
  61375. var canvas = document.createElement("canvas");
  61376. var context = canvas.getContext("2d");
  61377. if (!context) {
  61378. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61379. }
  61380. if (scene.isDisposed) {
  61381. return;
  61382. }
  61383. var bufferWidth = img.width;
  61384. var bufferHeight = img.height;
  61385. canvas.width = bufferWidth;
  61386. canvas.height = bufferHeight;
  61387. context.drawImage(img, 0, 0);
  61388. // Create VertexData from map data
  61389. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61390. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61391. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61392. width: width, height: height,
  61393. subdivisions: subdivisions,
  61394. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61395. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61396. });
  61397. vertexData.applyToMesh(ground, updatable);
  61398. //execute ready callback, if set
  61399. if (onReady) {
  61400. onReady(ground);
  61401. }
  61402. ground._setReady(true);
  61403. };
  61404. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61405. return ground;
  61406. };
  61407. /**
  61408. * Creates a polygon mesh
  61409. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61410. * * 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
  61411. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61412. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61413. * * 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)
  61414. * * Remember you can only change the shape positions, not their number when updating a polygon
  61415. * @param name defines the name of the mesh
  61416. * @param options defines the options used to create the mesh
  61417. * @param scene defines the hosting scene
  61418. * @returns the polygon mesh
  61419. */
  61420. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61421. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61422. var shape = options.shape;
  61423. var holes = options.holes || [];
  61424. var depth = options.depth || 0;
  61425. var contours = [];
  61426. var hole = [];
  61427. for (var i = 0; i < shape.length; i++) {
  61428. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61429. }
  61430. var epsilon = 0.00000001;
  61431. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61432. contours.pop();
  61433. }
  61434. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61435. for (var hNb = 0; hNb < holes.length; hNb++) {
  61436. hole = [];
  61437. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61438. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61439. }
  61440. polygonTriangulation.addHole(hole);
  61441. }
  61442. var polygon = polygonTriangulation.build(options.updatable, depth);
  61443. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61444. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61445. vertexData.applyToMesh(polygon, options.updatable);
  61446. return polygon;
  61447. };
  61448. ;
  61449. /**
  61450. * Creates an extruded polygon mesh, with depth in the Y direction.
  61451. * * 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)
  61452. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61453. * @param name defines the name of the mesh
  61454. * @param options defines the options used to create the mesh
  61455. * @param scene defines the hosting scene
  61456. * @returns the polygon mesh
  61457. */
  61458. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61459. return MeshBuilder.CreatePolygon(name, options, scene);
  61460. };
  61461. ;
  61462. /**
  61463. * Creates a tube mesh.
  61464. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61465. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61466. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61467. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61468. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61469. * * 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. It must return a radius value (positive float)
  61470. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61471. * * 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
  61472. * * 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
  61473. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61474. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61475. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61476. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61477. * @param name defines the name of the mesh
  61478. * @param options defines the options used to create the mesh
  61479. * @param scene defines the hosting scene
  61480. * @returns the tube mesh
  61481. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61482. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61483. */
  61484. MeshBuilder.CreateTube = function (name, options, scene) {
  61485. var path = options.path;
  61486. var instance = options.instance;
  61487. var radius = 1.0;
  61488. if (instance) {
  61489. radius = instance.radius;
  61490. }
  61491. if (options.radius !== undefined) {
  61492. radius = options.radius;
  61493. }
  61494. ;
  61495. var tessellation = options.tessellation || 64 | 0;
  61496. var radiusFunction = options.radiusFunction || null;
  61497. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61498. var invertUV = options.invertUV || false;
  61499. var updatable = options.updatable;
  61500. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61501. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61502. // tube geometry
  61503. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61504. var tangents = path3D.getTangents();
  61505. var normals = path3D.getNormals();
  61506. var distances = path3D.getDistances();
  61507. var pi2 = Math.PI * 2;
  61508. var step = pi2 / tessellation * arc;
  61509. var returnRadius = function () { return radius; };
  61510. var radiusFunctionFinal = radiusFunction || returnRadius;
  61511. var circlePath;
  61512. var rad;
  61513. var normal;
  61514. var rotated;
  61515. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61516. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61517. for (var i = 0; i < path.length; i++) {
  61518. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61519. circlePath = Array(); // current circle array
  61520. normal = normals[i]; // current normal
  61521. for (var t = 0; t < tessellation; t++) {
  61522. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61523. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61524. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61525. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61526. circlePath[t] = rotated;
  61527. }
  61528. circlePaths[index] = circlePath;
  61529. index++;
  61530. }
  61531. // cap
  61532. var capPath = function (nbPoints, pathIndex) {
  61533. var pointCap = Array();
  61534. for (var i = 0; i < nbPoints; i++) {
  61535. pointCap.push(path[pathIndex]);
  61536. }
  61537. return pointCap;
  61538. };
  61539. switch (cap) {
  61540. case BABYLON.Mesh.NO_CAP:
  61541. break;
  61542. case BABYLON.Mesh.CAP_START:
  61543. circlePaths[0] = capPath(tessellation, 0);
  61544. circlePaths[1] = circlePaths[2].slice(0);
  61545. break;
  61546. case BABYLON.Mesh.CAP_END:
  61547. circlePaths[index] = circlePaths[index - 1].slice(0);
  61548. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61549. break;
  61550. case BABYLON.Mesh.CAP_ALL:
  61551. circlePaths[0] = capPath(tessellation, 0);
  61552. circlePaths[1] = circlePaths[2].slice(0);
  61553. circlePaths[index] = circlePaths[index - 1].slice(0);
  61554. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61555. break;
  61556. default:
  61557. break;
  61558. }
  61559. return circlePaths;
  61560. };
  61561. var path3D;
  61562. var pathArray;
  61563. if (instance) { // tube update
  61564. var arc = options.arc || instance.arc;
  61565. path3D = (instance.path3D).update(path);
  61566. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61567. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61568. instance.path3D = path3D;
  61569. instance.pathArray = pathArray;
  61570. instance.arc = arc;
  61571. instance.radius = radius;
  61572. return instance;
  61573. }
  61574. // tube creation
  61575. path3D = new BABYLON.Path3D(path);
  61576. var newPathArray = new Array();
  61577. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61578. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61579. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61580. tube.pathArray = pathArray;
  61581. tube.path3D = path3D;
  61582. tube.tessellation = tessellation;
  61583. tube.cap = cap;
  61584. tube.arc = options.arc;
  61585. tube.radius = radius;
  61586. return tube;
  61587. };
  61588. /**
  61589. * Creates a polyhedron mesh
  61590. * * 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 to choose the wanted type
  61591. * * The parameter `size` (positive float, default 1) sets the polygon size
  61592. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61593. * * 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`
  61594. * * 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
  61595. * * 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)`)
  61596. * * 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
  61597. * * 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
  61598. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61599. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61600. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61601. * @param name defines the name of the mesh
  61602. * @param options defines the options used to create the mesh
  61603. * @param scene defines the hosting scene
  61604. * @returns the polyhedron mesh
  61605. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61606. */
  61607. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61608. var polyhedron = new BABYLON.Mesh(name, scene);
  61609. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61610. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61611. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61612. vertexData.applyToMesh(polyhedron, options.updatable);
  61613. return polyhedron;
  61614. };
  61615. /**
  61616. * Creates a decal mesh.
  61617. * 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
  61618. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61619. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61620. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61621. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61622. * @param name defines the name of the mesh
  61623. * @param sourceMesh defines the mesh where the decal must be applied
  61624. * @param options defines the options used to create the mesh
  61625. * @param scene defines the hosting scene
  61626. * @returns the decal mesh
  61627. * @see http://doc.babylonjs.com/how_to/decals
  61628. */
  61629. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61630. var indices = sourceMesh.getIndices();
  61631. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61632. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61633. var position = options.position || BABYLON.Vector3.Zero();
  61634. var normal = options.normal || BABYLON.Vector3.Up();
  61635. var size = options.size || BABYLON.Vector3.One();
  61636. var angle = options.angle || 0;
  61637. // Getting correct rotation
  61638. if (!normal) {
  61639. var target = new BABYLON.Vector3(0, 0, 1);
  61640. var camera = sourceMesh.getScene().activeCamera;
  61641. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61642. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61643. }
  61644. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61645. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61646. var pitch = Math.atan2(normal.y, len);
  61647. // Matrix
  61648. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61649. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61650. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61651. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61652. var vertexData = new BABYLON.VertexData();
  61653. vertexData.indices = [];
  61654. vertexData.positions = [];
  61655. vertexData.normals = [];
  61656. vertexData.uvs = [];
  61657. var currentVertexDataIndex = 0;
  61658. var extractDecalVector3 = function (indexId) {
  61659. var result = new BABYLON.PositionNormalVertex();
  61660. if (!indices || !positions || !normals) {
  61661. return result;
  61662. }
  61663. var vertexId = indices[indexId];
  61664. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61665. // Send vector to decal local world
  61666. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61667. // Get normal
  61668. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61669. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61670. return result;
  61671. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61672. var clip = function (vertices, axis) {
  61673. if (vertices.length === 0) {
  61674. return vertices;
  61675. }
  61676. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61677. var clipVertices = function (v0, v1) {
  61678. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61679. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61680. };
  61681. var result = new Array();
  61682. for (var index = 0; index < vertices.length; index += 3) {
  61683. var v1Out;
  61684. var v2Out;
  61685. var v3Out;
  61686. var total = 0;
  61687. var nV1 = null;
  61688. var nV2 = null;
  61689. var nV3 = null;
  61690. var nV4 = null;
  61691. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61692. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61693. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61694. v1Out = d1 > 0;
  61695. v2Out = d2 > 0;
  61696. v3Out = d3 > 0;
  61697. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61698. switch (total) {
  61699. case 0:
  61700. result.push(vertices[index]);
  61701. result.push(vertices[index + 1]);
  61702. result.push(vertices[index + 2]);
  61703. break;
  61704. case 1:
  61705. if (v1Out) {
  61706. nV1 = vertices[index + 1];
  61707. nV2 = vertices[index + 2];
  61708. nV3 = clipVertices(vertices[index], nV1);
  61709. nV4 = clipVertices(vertices[index], nV2);
  61710. }
  61711. if (v2Out) {
  61712. nV1 = vertices[index];
  61713. nV2 = vertices[index + 2];
  61714. nV3 = clipVertices(vertices[index + 1], nV1);
  61715. nV4 = clipVertices(vertices[index + 1], nV2);
  61716. result.push(nV3);
  61717. result.push(nV2.clone());
  61718. result.push(nV1.clone());
  61719. result.push(nV2.clone());
  61720. result.push(nV3.clone());
  61721. result.push(nV4);
  61722. break;
  61723. }
  61724. if (v3Out) {
  61725. nV1 = vertices[index];
  61726. nV2 = vertices[index + 1];
  61727. nV3 = clipVertices(vertices[index + 2], nV1);
  61728. nV4 = clipVertices(vertices[index + 2], nV2);
  61729. }
  61730. if (nV1 && nV2 && nV3 && nV4) {
  61731. result.push(nV1.clone());
  61732. result.push(nV2.clone());
  61733. result.push(nV3);
  61734. result.push(nV4);
  61735. result.push(nV3.clone());
  61736. result.push(nV2.clone());
  61737. }
  61738. break;
  61739. case 2:
  61740. if (!v1Out) {
  61741. nV1 = vertices[index].clone();
  61742. nV2 = clipVertices(nV1, vertices[index + 1]);
  61743. nV3 = clipVertices(nV1, vertices[index + 2]);
  61744. result.push(nV1);
  61745. result.push(nV2);
  61746. result.push(nV3);
  61747. }
  61748. if (!v2Out) {
  61749. nV1 = vertices[index + 1].clone();
  61750. nV2 = clipVertices(nV1, vertices[index + 2]);
  61751. nV3 = clipVertices(nV1, vertices[index]);
  61752. result.push(nV1);
  61753. result.push(nV2);
  61754. result.push(nV3);
  61755. }
  61756. if (!v3Out) {
  61757. nV1 = vertices[index + 2].clone();
  61758. nV2 = clipVertices(nV1, vertices[index]);
  61759. nV3 = clipVertices(nV1, vertices[index + 1]);
  61760. result.push(nV1);
  61761. result.push(nV2);
  61762. result.push(nV3);
  61763. }
  61764. break;
  61765. case 3:
  61766. break;
  61767. }
  61768. }
  61769. return result;
  61770. };
  61771. for (var index = 0; index < indices.length; index += 3) {
  61772. var faceVertices = new Array();
  61773. faceVertices.push(extractDecalVector3(index));
  61774. faceVertices.push(extractDecalVector3(index + 1));
  61775. faceVertices.push(extractDecalVector3(index + 2));
  61776. // Clip
  61777. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61778. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61779. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61780. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61781. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61782. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61783. if (faceVertices.length === 0) {
  61784. continue;
  61785. }
  61786. // Add UVs and get back to world
  61787. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61788. var vertex = faceVertices[vIndex];
  61789. //TODO check for Int32Array | Uint32Array | Uint16Array
  61790. vertexData.indices.push(currentVertexDataIndex);
  61791. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61792. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61793. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61794. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61795. currentVertexDataIndex++;
  61796. }
  61797. }
  61798. // Return mesh
  61799. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61800. vertexData.applyToMesh(decal);
  61801. decal.position = position.clone();
  61802. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61803. return decal;
  61804. };
  61805. // Privates
  61806. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61807. // extrusion geometry
  61808. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61809. var tangents = path3D.getTangents();
  61810. var normals = path3D.getNormals();
  61811. var binormals = path3D.getBinormals();
  61812. var distances = path3D.getDistances();
  61813. var angle = 0;
  61814. var returnScale = function () { return scale !== null ? scale : 1; };
  61815. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61816. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61817. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61818. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61819. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61820. for (var i = 0; i < curve.length; i++) {
  61821. var shapePath = new Array();
  61822. var angleStep = rotate(i, distances[i]);
  61823. var scaleRatio = scl(i, distances[i]);
  61824. for (var p = 0; p < shape.length; p++) {
  61825. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61826. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61827. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61828. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61829. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61830. shapePath[p] = rotated;
  61831. }
  61832. shapePaths[index] = shapePath;
  61833. angle += angleStep;
  61834. index++;
  61835. }
  61836. // cap
  61837. var capPath = function (shapePath) {
  61838. var pointCap = Array();
  61839. var barycenter = BABYLON.Vector3.Zero();
  61840. var i;
  61841. for (i = 0; i < shapePath.length; i++) {
  61842. barycenter.addInPlace(shapePath[i]);
  61843. }
  61844. barycenter.scaleInPlace(1.0 / shapePath.length);
  61845. for (i = 0; i < shapePath.length; i++) {
  61846. pointCap.push(barycenter);
  61847. }
  61848. return pointCap;
  61849. };
  61850. switch (cap) {
  61851. case BABYLON.Mesh.NO_CAP:
  61852. break;
  61853. case BABYLON.Mesh.CAP_START:
  61854. shapePaths[0] = capPath(shapePaths[2]);
  61855. shapePaths[1] = shapePaths[2];
  61856. break;
  61857. case BABYLON.Mesh.CAP_END:
  61858. shapePaths[index] = shapePaths[index - 1];
  61859. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61860. break;
  61861. case BABYLON.Mesh.CAP_ALL:
  61862. shapePaths[0] = capPath(shapePaths[2]);
  61863. shapePaths[1] = shapePaths[2];
  61864. shapePaths[index] = shapePaths[index - 1];
  61865. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61866. break;
  61867. default:
  61868. break;
  61869. }
  61870. return shapePaths;
  61871. };
  61872. var path3D;
  61873. var pathArray;
  61874. if (instance) { // instance update
  61875. path3D = (instance.path3D).update(curve);
  61876. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61877. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61878. return instance;
  61879. }
  61880. // extruded shape creation
  61881. path3D = new BABYLON.Path3D(curve);
  61882. var newShapePaths = new Array();
  61883. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61884. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61885. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61886. extrudedGeneric.pathArray = pathArray;
  61887. extrudedGeneric.path3D = path3D;
  61888. extrudedGeneric.cap = cap;
  61889. return extrudedGeneric;
  61890. };
  61891. return MeshBuilder;
  61892. }());
  61893. BABYLON.MeshBuilder = MeshBuilder;
  61894. })(BABYLON || (BABYLON = {}));
  61895. //# sourceMappingURL=babylon.meshBuilder.js.map
  61896. var BABYLON;
  61897. (function (BABYLON) {
  61898. /**
  61899. * Draco compression (https://google.github.io/draco/)
  61900. */
  61901. var DracoCompression = /** @class */ (function () {
  61902. /**
  61903. * Constructor
  61904. */
  61905. function DracoCompression() {
  61906. }
  61907. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61908. /**
  61909. * Returns true if the decoder is available.
  61910. */
  61911. get: function () {
  61912. if (typeof DracoDecoderModule !== "undefined") {
  61913. return true;
  61914. }
  61915. var decoder = DracoCompression.Configuration.decoder;
  61916. if (decoder) {
  61917. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61918. return true;
  61919. }
  61920. if (decoder.fallbackUrl) {
  61921. return true;
  61922. }
  61923. }
  61924. return false;
  61925. },
  61926. enumerable: true,
  61927. configurable: true
  61928. });
  61929. /**
  61930. * Stop all async operations and release resources.
  61931. */
  61932. DracoCompression.prototype.dispose = function () {
  61933. };
  61934. /**
  61935. * Decode Draco compressed mesh data to vertex data.
  61936. * @param data The array buffer view for the Draco compression data
  61937. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61938. * @returns A promise that resolves with the decoded vertex data
  61939. */
  61940. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61941. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61942. var module = wrappedModule.module;
  61943. var vertexData = new BABYLON.VertexData();
  61944. var buffer = new module.DecoderBuffer();
  61945. buffer.Init(data, data.byteLength);
  61946. var decoder = new module.Decoder();
  61947. var geometry;
  61948. var status;
  61949. try {
  61950. var type = decoder.GetEncodedGeometryType(buffer);
  61951. switch (type) {
  61952. case module.TRIANGULAR_MESH:
  61953. geometry = new module.Mesh();
  61954. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61955. break;
  61956. case module.POINT_CLOUD:
  61957. geometry = new module.PointCloud();
  61958. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61959. break;
  61960. default:
  61961. throw new Error("Invalid geometry type " + type);
  61962. }
  61963. if (!status.ok() || !geometry.ptr) {
  61964. throw new Error(status.error_msg());
  61965. }
  61966. var numPoints = geometry.num_points();
  61967. if (type === module.TRIANGULAR_MESH) {
  61968. var numFaces = geometry.num_faces();
  61969. var faceIndices = new module.DracoInt32Array();
  61970. try {
  61971. var indices = new Uint32Array(numFaces * 3);
  61972. for (var i = 0; i < numFaces; i++) {
  61973. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61974. var offset = i * 3;
  61975. indices[offset + 0] = faceIndices.GetValue(0);
  61976. indices[offset + 1] = faceIndices.GetValue(1);
  61977. indices[offset + 2] = faceIndices.GetValue(2);
  61978. }
  61979. vertexData.indices = indices;
  61980. }
  61981. finally {
  61982. module.destroy(faceIndices);
  61983. }
  61984. }
  61985. for (var kind in attributes) {
  61986. var uniqueId = attributes[kind];
  61987. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61988. var dracoData = new module.DracoFloat32Array();
  61989. try {
  61990. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61991. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61992. for (var i = 0; i < babylonData.length; i++) {
  61993. babylonData[i] = dracoData.GetValue(i);
  61994. }
  61995. vertexData.set(babylonData, kind);
  61996. }
  61997. finally {
  61998. module.destroy(dracoData);
  61999. }
  62000. }
  62001. }
  62002. finally {
  62003. if (geometry) {
  62004. module.destroy(geometry);
  62005. }
  62006. module.destroy(decoder);
  62007. module.destroy(buffer);
  62008. }
  62009. return vertexData;
  62010. });
  62011. };
  62012. DracoCompression._GetDecoderModule = function () {
  62013. if (!DracoCompression._DecoderModulePromise) {
  62014. var promise = null;
  62015. var config_1 = {};
  62016. if (typeof DracoDecoderModule !== "undefined") {
  62017. promise = Promise.resolve();
  62018. }
  62019. else {
  62020. var decoder = DracoCompression.Configuration.decoder;
  62021. if (decoder) {
  62022. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62023. promise = Promise.all([
  62024. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62025. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62026. config_1.wasmBinary = data;
  62027. })
  62028. ]);
  62029. }
  62030. else if (decoder.fallbackUrl) {
  62031. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62032. }
  62033. }
  62034. }
  62035. if (!promise) {
  62036. throw new Error("Draco decoder module is not available");
  62037. }
  62038. DracoCompression._DecoderModulePromise = promise.then(function () {
  62039. return new Promise(function (resolve) {
  62040. config_1.onModuleLoaded = function (decoderModule) {
  62041. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62042. resolve({ module: decoderModule });
  62043. };
  62044. DracoDecoderModule(config_1);
  62045. });
  62046. });
  62047. }
  62048. return DracoCompression._DecoderModulePromise;
  62049. };
  62050. DracoCompression._LoadScriptAsync = function (url) {
  62051. return new Promise(function (resolve, reject) {
  62052. BABYLON.Tools.LoadScript(url, function () {
  62053. resolve();
  62054. }, function (message) {
  62055. reject(new Error(message));
  62056. });
  62057. });
  62058. };
  62059. DracoCompression._LoadFileAsync = function (url) {
  62060. return new Promise(function (resolve, reject) {
  62061. BABYLON.Tools.LoadFile(url, function (data) {
  62062. resolve(data);
  62063. }, undefined, undefined, true, function (request, exception) {
  62064. reject(exception);
  62065. });
  62066. });
  62067. };
  62068. /**
  62069. * The configuration.
  62070. */
  62071. DracoCompression.Configuration = {
  62072. decoder: {
  62073. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62074. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62075. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62076. }
  62077. };
  62078. return DracoCompression;
  62079. }());
  62080. BABYLON.DracoCompression = DracoCompression;
  62081. })(BABYLON || (BABYLON = {}));
  62082. //# sourceMappingURL=babylon.dracoCompression.js.map
  62083. var BABYLON;
  62084. (function (BABYLON) {
  62085. var AudioEngine = /** @class */ (function () {
  62086. function AudioEngine() {
  62087. this._audioContext = null;
  62088. this._audioContextInitialized = false;
  62089. this.canUseWebAudio = false;
  62090. this.WarnedWebAudioUnsupported = false;
  62091. this.unlocked = false;
  62092. this.isMP3supported = false;
  62093. this.isOGGsupported = false;
  62094. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62095. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62096. this.canUseWebAudio = true;
  62097. }
  62098. var audioElem = document.createElement('audio');
  62099. try {
  62100. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62101. this.isMP3supported = true;
  62102. }
  62103. }
  62104. catch (e) {
  62105. // protect error during capability check.
  62106. }
  62107. try {
  62108. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62109. this.isOGGsupported = true;
  62110. }
  62111. }
  62112. catch (e) {
  62113. // protect error during capability check.
  62114. }
  62115. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62116. this._unlockiOSaudio();
  62117. }
  62118. else {
  62119. this.unlocked = true;
  62120. }
  62121. }
  62122. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62123. get: function () {
  62124. if (!this._audioContextInitialized) {
  62125. this._initializeAudioContext();
  62126. }
  62127. return this._audioContext;
  62128. },
  62129. enumerable: true,
  62130. configurable: true
  62131. });
  62132. AudioEngine.prototype._unlockiOSaudio = function () {
  62133. var _this = this;
  62134. var unlockaudio = function () {
  62135. if (!_this.audioContext) {
  62136. return;
  62137. }
  62138. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62139. var source = _this.audioContext.createBufferSource();
  62140. source.buffer = buffer;
  62141. source.connect(_this.audioContext.destination);
  62142. source.start(0);
  62143. setTimeout(function () {
  62144. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62145. _this.unlocked = true;
  62146. window.removeEventListener('touchend', unlockaudio, false);
  62147. if (_this.onAudioUnlocked) {
  62148. _this.onAudioUnlocked();
  62149. }
  62150. }
  62151. }, 0);
  62152. };
  62153. window.addEventListener('touchend', unlockaudio, false);
  62154. };
  62155. AudioEngine.prototype._initializeAudioContext = function () {
  62156. try {
  62157. if (this.canUseWebAudio) {
  62158. this._audioContext = new AudioContext();
  62159. // create a global volume gain node
  62160. this.masterGain = this._audioContext.createGain();
  62161. this.masterGain.gain.value = 1;
  62162. this.masterGain.connect(this._audioContext.destination);
  62163. this._audioContextInitialized = true;
  62164. }
  62165. }
  62166. catch (e) {
  62167. this.canUseWebAudio = false;
  62168. BABYLON.Tools.Error("Web Audio: " + e.message);
  62169. }
  62170. };
  62171. AudioEngine.prototype.dispose = function () {
  62172. if (this.canUseWebAudio && this._audioContextInitialized) {
  62173. if (this._connectedAnalyser && this._audioContext) {
  62174. this._connectedAnalyser.stopDebugCanvas();
  62175. this._connectedAnalyser.dispose();
  62176. this.masterGain.disconnect();
  62177. this.masterGain.connect(this._audioContext.destination);
  62178. this._connectedAnalyser = null;
  62179. }
  62180. this.masterGain.gain.value = 1;
  62181. }
  62182. this.WarnedWebAudioUnsupported = false;
  62183. };
  62184. AudioEngine.prototype.getGlobalVolume = function () {
  62185. if (this.canUseWebAudio && this._audioContextInitialized) {
  62186. return this.masterGain.gain.value;
  62187. }
  62188. else {
  62189. return -1;
  62190. }
  62191. };
  62192. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62193. if (this.canUseWebAudio && this._audioContextInitialized) {
  62194. this.masterGain.gain.value = newVolume;
  62195. }
  62196. };
  62197. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62198. if (this._connectedAnalyser) {
  62199. this._connectedAnalyser.stopDebugCanvas();
  62200. }
  62201. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62202. this._connectedAnalyser = analyser;
  62203. this.masterGain.disconnect();
  62204. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62205. }
  62206. };
  62207. return AudioEngine;
  62208. }());
  62209. BABYLON.AudioEngine = AudioEngine;
  62210. })(BABYLON || (BABYLON = {}));
  62211. //# sourceMappingURL=babylon.audioEngine.js.map
  62212. var BABYLON;
  62213. (function (BABYLON) {
  62214. var Sound = /** @class */ (function () {
  62215. /**
  62216. * Create a sound and attach it to a scene
  62217. * @param name Name of your sound
  62218. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62219. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62220. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62221. */
  62222. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62223. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62224. var _this = this;
  62225. this.autoplay = false;
  62226. this.loop = false;
  62227. this.useCustomAttenuation = false;
  62228. this.spatialSound = false;
  62229. this.refDistance = 1;
  62230. this.rolloffFactor = 1;
  62231. this.maxDistance = 100;
  62232. this.distanceModel = "linear";
  62233. this._panningModel = "equalpower";
  62234. this._playbackRate = 1;
  62235. this._streaming = false;
  62236. this._startTime = 0;
  62237. this._startOffset = 0;
  62238. this._position = BABYLON.Vector3.Zero();
  62239. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62240. this._volume = 1;
  62241. this._isReadyToPlay = false;
  62242. this.isPlaying = false;
  62243. this.isPaused = false;
  62244. this._isDirectional = false;
  62245. // Used if you'd like to create a directional sound.
  62246. // If not set, the sound will be omnidirectional
  62247. this._coneInnerAngle = 360;
  62248. this._coneOuterAngle = 360;
  62249. this._coneOuterGain = 0;
  62250. this._isOutputConnected = false;
  62251. this._urlType = "Unknown";
  62252. this.name = name;
  62253. this._scene = scene;
  62254. this._readyToPlayCallback = readyToPlayCallback;
  62255. // Default custom attenuation function is a linear attenuation
  62256. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62257. if (currentDistance < maxDistance) {
  62258. return currentVolume * (1 - currentDistance / maxDistance);
  62259. }
  62260. else {
  62261. return 0;
  62262. }
  62263. };
  62264. if (options) {
  62265. this.autoplay = options.autoplay || false;
  62266. this.loop = options.loop || false;
  62267. // if volume === 0, we need another way to check this option
  62268. if (options.volume !== undefined) {
  62269. this._volume = options.volume;
  62270. }
  62271. this.spatialSound = options.spatialSound || false;
  62272. this.maxDistance = options.maxDistance || 100;
  62273. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62274. this.rolloffFactor = options.rolloffFactor || 1;
  62275. this.refDistance = options.refDistance || 1;
  62276. this.distanceModel = options.distanceModel || "linear";
  62277. this._playbackRate = options.playbackRate || 1;
  62278. this._streaming = options.streaming || false;
  62279. }
  62280. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62281. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62282. this._soundGain.gain.value = this._volume;
  62283. this._inputAudioNode = this._soundGain;
  62284. this._ouputAudioNode = this._soundGain;
  62285. if (this.spatialSound) {
  62286. this._createSpatialParameters();
  62287. }
  62288. this._scene.mainSoundTrack.AddSound(this);
  62289. var validParameter = true;
  62290. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62291. if (urlOrArrayBuffer) {
  62292. try {
  62293. if (typeof (urlOrArrayBuffer) === "string")
  62294. this._urlType = "String";
  62295. if (Array.isArray(urlOrArrayBuffer))
  62296. this._urlType = "Array";
  62297. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62298. this._urlType = "ArrayBuffer";
  62299. var urls = [];
  62300. var codecSupportedFound = false;
  62301. switch (this._urlType) {
  62302. case "ArrayBuffer":
  62303. if (urlOrArrayBuffer.byteLength > 0) {
  62304. codecSupportedFound = true;
  62305. this._soundLoaded(urlOrArrayBuffer);
  62306. }
  62307. break;
  62308. case "String":
  62309. urls.push(urlOrArrayBuffer);
  62310. case "Array":
  62311. if (urls.length === 0)
  62312. urls = urlOrArrayBuffer;
  62313. // If we found a supported format, we load it immediately and stop the loop
  62314. for (var i = 0; i < urls.length; i++) {
  62315. var url = urls[i];
  62316. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62317. codecSupportedFound = true;
  62318. }
  62319. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62320. codecSupportedFound = true;
  62321. }
  62322. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62323. codecSupportedFound = true;
  62324. }
  62325. if (url.indexOf("blob:") !== -1) {
  62326. codecSupportedFound = true;
  62327. }
  62328. if (codecSupportedFound) {
  62329. // Loading sound using XHR2
  62330. if (!this._streaming) {
  62331. this._scene._loadFile(url, function (data) {
  62332. _this._soundLoaded(data);
  62333. }, undefined, true, true, function (exception) {
  62334. if (exception) {
  62335. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62336. }
  62337. BABYLON.Tools.Error("Sound creation aborted.");
  62338. _this._scene.mainSoundTrack.RemoveSound(_this);
  62339. });
  62340. }
  62341. // Streaming sound using HTML5 Audio tag
  62342. else {
  62343. this._htmlAudioElement = new Audio(url);
  62344. this._htmlAudioElement.controls = false;
  62345. this._htmlAudioElement.loop = this.loop;
  62346. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62347. this._htmlAudioElement.preload = "auto";
  62348. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62349. _this._isReadyToPlay = true;
  62350. if (_this.autoplay) {
  62351. _this.play();
  62352. }
  62353. if (_this._readyToPlayCallback) {
  62354. _this._readyToPlayCallback();
  62355. }
  62356. });
  62357. document.body.appendChild(this._htmlAudioElement);
  62358. }
  62359. break;
  62360. }
  62361. }
  62362. break;
  62363. default:
  62364. validParameter = false;
  62365. break;
  62366. }
  62367. if (!validParameter) {
  62368. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62369. }
  62370. else {
  62371. if (!codecSupportedFound) {
  62372. this._isReadyToPlay = true;
  62373. // Simulating a ready to play event to avoid breaking code path
  62374. if (this._readyToPlayCallback) {
  62375. window.setTimeout(function () {
  62376. if (_this._readyToPlayCallback) {
  62377. _this._readyToPlayCallback();
  62378. }
  62379. }, 1000);
  62380. }
  62381. }
  62382. }
  62383. }
  62384. catch (ex) {
  62385. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62386. this._scene.mainSoundTrack.RemoveSound(this);
  62387. }
  62388. }
  62389. }
  62390. else {
  62391. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62392. this._scene.mainSoundTrack.AddSound(this);
  62393. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62394. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62395. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62396. }
  62397. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62398. if (this._readyToPlayCallback) {
  62399. window.setTimeout(function () {
  62400. if (_this._readyToPlayCallback) {
  62401. _this._readyToPlayCallback();
  62402. }
  62403. }, 1000);
  62404. }
  62405. }
  62406. }
  62407. Sound.prototype.dispose = function () {
  62408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62409. if (this.isPlaying) {
  62410. this.stop();
  62411. }
  62412. this._isReadyToPlay = false;
  62413. if (this.soundTrackId === -1) {
  62414. this._scene.mainSoundTrack.RemoveSound(this);
  62415. }
  62416. else {
  62417. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62418. }
  62419. if (this._soundGain) {
  62420. this._soundGain.disconnect();
  62421. this._soundGain = null;
  62422. }
  62423. if (this._soundPanner) {
  62424. this._soundPanner.disconnect();
  62425. this._soundPanner = null;
  62426. }
  62427. if (this._soundSource) {
  62428. this._soundSource.disconnect();
  62429. this._soundSource = null;
  62430. }
  62431. this._audioBuffer = null;
  62432. if (this._htmlAudioElement) {
  62433. this._htmlAudioElement.pause();
  62434. this._htmlAudioElement.src = "";
  62435. document.body.removeChild(this._htmlAudioElement);
  62436. }
  62437. if (this._connectedMesh && this._registerFunc) {
  62438. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62439. this._connectedMesh = null;
  62440. }
  62441. }
  62442. };
  62443. Sound.prototype.isReady = function () {
  62444. return this._isReadyToPlay;
  62445. };
  62446. Sound.prototype._soundLoaded = function (audioData) {
  62447. var _this = this;
  62448. if (!BABYLON.Engine.audioEngine.audioContext) {
  62449. return;
  62450. }
  62451. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62452. _this._audioBuffer = buffer;
  62453. _this._isReadyToPlay = true;
  62454. if (_this.autoplay) {
  62455. _this.play();
  62456. }
  62457. if (_this._readyToPlayCallback) {
  62458. _this._readyToPlayCallback();
  62459. }
  62460. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62461. };
  62462. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62464. this._audioBuffer = audioBuffer;
  62465. this._isReadyToPlay = true;
  62466. }
  62467. };
  62468. Sound.prototype.updateOptions = function (options) {
  62469. if (options) {
  62470. this.loop = options.loop || this.loop;
  62471. this.maxDistance = options.maxDistance || this.maxDistance;
  62472. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62473. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62474. this.refDistance = options.refDistance || this.refDistance;
  62475. this.distanceModel = options.distanceModel || this.distanceModel;
  62476. this._playbackRate = options.playbackRate || this._playbackRate;
  62477. this._updateSpatialParameters();
  62478. if (this.isPlaying) {
  62479. if (this._streaming) {
  62480. this._htmlAudioElement.playbackRate = this._playbackRate;
  62481. }
  62482. else {
  62483. if (this._soundSource) {
  62484. this._soundSource.playbackRate.value = this._playbackRate;
  62485. }
  62486. }
  62487. }
  62488. }
  62489. };
  62490. Sound.prototype._createSpatialParameters = function () {
  62491. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62492. if (this._scene.headphone) {
  62493. this._panningModel = "HRTF";
  62494. }
  62495. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62496. this._updateSpatialParameters();
  62497. this._soundPanner.connect(this._ouputAudioNode);
  62498. this._inputAudioNode = this._soundPanner;
  62499. }
  62500. };
  62501. Sound.prototype._updateSpatialParameters = function () {
  62502. if (this.spatialSound && this._soundPanner) {
  62503. if (this.useCustomAttenuation) {
  62504. // Tricks to disable in a way embedded Web Audio attenuation
  62505. this._soundPanner.distanceModel = "linear";
  62506. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62507. this._soundPanner.refDistance = 1;
  62508. this._soundPanner.rolloffFactor = 1;
  62509. this._soundPanner.panningModel = this._panningModel;
  62510. }
  62511. else {
  62512. this._soundPanner.distanceModel = this.distanceModel;
  62513. this._soundPanner.maxDistance = this.maxDistance;
  62514. this._soundPanner.refDistance = this.refDistance;
  62515. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62516. this._soundPanner.panningModel = this._panningModel;
  62517. }
  62518. }
  62519. };
  62520. Sound.prototype.switchPanningModelToHRTF = function () {
  62521. this._panningModel = "HRTF";
  62522. this._switchPanningModel();
  62523. };
  62524. Sound.prototype.switchPanningModelToEqualPower = function () {
  62525. this._panningModel = "equalpower";
  62526. this._switchPanningModel();
  62527. };
  62528. Sound.prototype._switchPanningModel = function () {
  62529. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62530. this._soundPanner.panningModel = this._panningModel;
  62531. }
  62532. };
  62533. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62534. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62535. if (this._isOutputConnected) {
  62536. this._ouputAudioNode.disconnect();
  62537. }
  62538. this._ouputAudioNode.connect(soundTrackAudioNode);
  62539. this._isOutputConnected = true;
  62540. }
  62541. };
  62542. /**
  62543. * Transform this sound into a directional source
  62544. * @param coneInnerAngle Size of the inner cone in degree
  62545. * @param coneOuterAngle Size of the outer cone in degree
  62546. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62547. */
  62548. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62549. if (coneOuterAngle < coneInnerAngle) {
  62550. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62551. return;
  62552. }
  62553. this._coneInnerAngle = coneInnerAngle;
  62554. this._coneOuterAngle = coneOuterAngle;
  62555. this._coneOuterGain = coneOuterGain;
  62556. this._isDirectional = true;
  62557. if (this.isPlaying && this.loop) {
  62558. this.stop();
  62559. this.play();
  62560. }
  62561. };
  62562. Sound.prototype.setPosition = function (newPosition) {
  62563. this._position = newPosition;
  62564. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62565. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62566. }
  62567. };
  62568. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62569. this._localDirection = newLocalDirection;
  62570. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62571. this._updateDirection();
  62572. }
  62573. };
  62574. Sound.prototype._updateDirection = function () {
  62575. if (!this._connectedMesh || !this._soundPanner) {
  62576. return;
  62577. }
  62578. var mat = this._connectedMesh.getWorldMatrix();
  62579. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62580. direction.normalize();
  62581. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62582. };
  62583. Sound.prototype.updateDistanceFromListener = function () {
  62584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62585. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62586. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62587. }
  62588. };
  62589. Sound.prototype.setAttenuationFunction = function (callback) {
  62590. this._customAttenuationFunction = callback;
  62591. };
  62592. /**
  62593. * Play the sound
  62594. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62595. * @param offset (optional) Start the sound setting it at a specific time
  62596. */
  62597. Sound.prototype.play = function (time, offset) {
  62598. var _this = this;
  62599. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62600. try {
  62601. if (this._startOffset < 0) {
  62602. time = -this._startOffset;
  62603. this._startOffset = 0;
  62604. }
  62605. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62606. if (!this._soundSource || !this._streamingSource) {
  62607. if (this.spatialSound && this._soundPanner) {
  62608. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62609. if (this._isDirectional) {
  62610. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62611. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62612. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62613. if (this._connectedMesh) {
  62614. this._updateDirection();
  62615. }
  62616. else {
  62617. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62618. }
  62619. }
  62620. }
  62621. }
  62622. if (this._streaming) {
  62623. if (!this._streamingSource) {
  62624. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62625. this._htmlAudioElement.onended = function () { _this._onended(); };
  62626. this._htmlAudioElement.playbackRate = this._playbackRate;
  62627. }
  62628. this._streamingSource.disconnect();
  62629. this._streamingSource.connect(this._inputAudioNode);
  62630. this._htmlAudioElement.play();
  62631. }
  62632. else {
  62633. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62634. this._soundSource.buffer = this._audioBuffer;
  62635. this._soundSource.connect(this._inputAudioNode);
  62636. this._soundSource.loop = this.loop;
  62637. this._soundSource.playbackRate.value = this._playbackRate;
  62638. this._soundSource.onended = function () { _this._onended(); };
  62639. if (this._soundSource.buffer) {
  62640. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62641. }
  62642. }
  62643. this._startTime = startTime;
  62644. this.isPlaying = true;
  62645. this.isPaused = false;
  62646. }
  62647. catch (ex) {
  62648. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62649. }
  62650. }
  62651. };
  62652. Sound.prototype._onended = function () {
  62653. this.isPlaying = false;
  62654. if (this.onended) {
  62655. this.onended();
  62656. }
  62657. };
  62658. /**
  62659. * Stop the sound
  62660. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62661. */
  62662. Sound.prototype.stop = function (time) {
  62663. if (this.isPlaying) {
  62664. if (this._streaming) {
  62665. this._htmlAudioElement.pause();
  62666. // Test needed for Firefox or it will generate an Invalid State Error
  62667. if (this._htmlAudioElement.currentTime > 0) {
  62668. this._htmlAudioElement.currentTime = 0;
  62669. }
  62670. }
  62671. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62672. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62673. this._soundSource.stop(stopTime);
  62674. this._soundSource.onended = function () { };
  62675. if (!this.isPaused) {
  62676. this._startOffset = 0;
  62677. }
  62678. }
  62679. this.isPlaying = false;
  62680. }
  62681. };
  62682. Sound.prototype.pause = function () {
  62683. if (this.isPlaying) {
  62684. this.isPaused = true;
  62685. if (this._streaming) {
  62686. this._htmlAudioElement.pause();
  62687. }
  62688. else if (BABYLON.Engine.audioEngine.audioContext) {
  62689. this.stop(0);
  62690. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62691. }
  62692. }
  62693. };
  62694. Sound.prototype.setVolume = function (newVolume, time) {
  62695. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62696. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62697. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62698. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62699. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62700. }
  62701. else {
  62702. this._soundGain.gain.value = newVolume;
  62703. }
  62704. }
  62705. this._volume = newVolume;
  62706. };
  62707. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62708. this._playbackRate = newPlaybackRate;
  62709. if (this.isPlaying) {
  62710. if (this._streaming) {
  62711. this._htmlAudioElement.playbackRate = this._playbackRate;
  62712. }
  62713. else if (this._soundSource) {
  62714. this._soundSource.playbackRate.value = this._playbackRate;
  62715. }
  62716. }
  62717. };
  62718. Sound.prototype.getVolume = function () {
  62719. return this._volume;
  62720. };
  62721. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62722. var _this = this;
  62723. if (this._connectedMesh && this._registerFunc) {
  62724. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62725. this._registerFunc = null;
  62726. }
  62727. this._connectedMesh = meshToConnectTo;
  62728. if (!this.spatialSound) {
  62729. this.spatialSound = true;
  62730. this._createSpatialParameters();
  62731. if (this.isPlaying && this.loop) {
  62732. this.stop();
  62733. this.play();
  62734. }
  62735. }
  62736. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62737. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62738. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62739. };
  62740. Sound.prototype.detachFromMesh = function () {
  62741. if (this._connectedMesh && this._registerFunc) {
  62742. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62743. this._registerFunc = null;
  62744. this._connectedMesh = null;
  62745. }
  62746. };
  62747. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62748. if (!node.getBoundingInfo) {
  62749. return;
  62750. }
  62751. var mesh = node;
  62752. var boundingInfo = mesh.getBoundingInfo();
  62753. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62754. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62755. this._updateDirection();
  62756. }
  62757. };
  62758. Sound.prototype.clone = function () {
  62759. var _this = this;
  62760. if (!this._streaming) {
  62761. var setBufferAndRun = function () {
  62762. if (_this._isReadyToPlay) {
  62763. clonedSound._audioBuffer = _this.getAudioBuffer();
  62764. clonedSound._isReadyToPlay = true;
  62765. if (clonedSound.autoplay) {
  62766. clonedSound.play();
  62767. }
  62768. }
  62769. else {
  62770. window.setTimeout(setBufferAndRun, 300);
  62771. }
  62772. };
  62773. var currentOptions = {
  62774. autoplay: this.autoplay, loop: this.loop,
  62775. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62776. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62777. refDistance: this.refDistance, distanceModel: this.distanceModel
  62778. };
  62779. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62780. if (this.useCustomAttenuation) {
  62781. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62782. }
  62783. clonedSound.setPosition(this._position);
  62784. clonedSound.setPlaybackRate(this._playbackRate);
  62785. setBufferAndRun();
  62786. return clonedSound;
  62787. }
  62788. // Can't clone a streaming sound
  62789. else {
  62790. return null;
  62791. }
  62792. };
  62793. Sound.prototype.getAudioBuffer = function () {
  62794. return this._audioBuffer;
  62795. };
  62796. Sound.prototype.serialize = function () {
  62797. var serializationObject = {
  62798. name: this.name,
  62799. url: this.name,
  62800. autoplay: this.autoplay,
  62801. loop: this.loop,
  62802. volume: this._volume,
  62803. spatialSound: this.spatialSound,
  62804. maxDistance: this.maxDistance,
  62805. rolloffFactor: this.rolloffFactor,
  62806. refDistance: this.refDistance,
  62807. distanceModel: this.distanceModel,
  62808. playbackRate: this._playbackRate,
  62809. panningModel: this._panningModel,
  62810. soundTrackId: this.soundTrackId
  62811. };
  62812. if (this.spatialSound) {
  62813. if (this._connectedMesh)
  62814. serializationObject.connectedMeshId = this._connectedMesh.id;
  62815. serializationObject.position = this._position.asArray();
  62816. serializationObject.refDistance = this.refDistance;
  62817. serializationObject.distanceModel = this.distanceModel;
  62818. serializationObject.isDirectional = this._isDirectional;
  62819. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62820. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62821. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62822. serializationObject.coneOuterGain = this._coneOuterGain;
  62823. }
  62824. return serializationObject;
  62825. };
  62826. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62827. var soundName = parsedSound.name;
  62828. var soundUrl;
  62829. if (parsedSound.url) {
  62830. soundUrl = rootUrl + parsedSound.url;
  62831. }
  62832. else {
  62833. soundUrl = rootUrl + soundName;
  62834. }
  62835. var options = {
  62836. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62837. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62838. rolloffFactor: parsedSound.rolloffFactor,
  62839. refDistance: parsedSound.refDistance,
  62840. distanceModel: parsedSound.distanceModel,
  62841. playbackRate: parsedSound.playbackRate
  62842. };
  62843. var newSound;
  62844. if (!sourceSound) {
  62845. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62846. scene._addPendingData(newSound);
  62847. }
  62848. else {
  62849. var setBufferAndRun = function () {
  62850. if (sourceSound._isReadyToPlay) {
  62851. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62852. newSound._isReadyToPlay = true;
  62853. if (newSound.autoplay) {
  62854. newSound.play();
  62855. }
  62856. }
  62857. else {
  62858. window.setTimeout(setBufferAndRun, 300);
  62859. }
  62860. };
  62861. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62862. setBufferAndRun();
  62863. }
  62864. if (parsedSound.position) {
  62865. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62866. newSound.setPosition(soundPosition);
  62867. }
  62868. if (parsedSound.isDirectional) {
  62869. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62870. if (parsedSound.localDirectionToMesh) {
  62871. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62872. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62873. }
  62874. }
  62875. if (parsedSound.connectedMeshId) {
  62876. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62877. if (connectedMesh) {
  62878. newSound.attachToMesh(connectedMesh);
  62879. }
  62880. }
  62881. return newSound;
  62882. };
  62883. return Sound;
  62884. }());
  62885. BABYLON.Sound = Sound;
  62886. })(BABYLON || (BABYLON = {}));
  62887. //# sourceMappingURL=babylon.sound.js.map
  62888. var BABYLON;
  62889. (function (BABYLON) {
  62890. var SoundTrack = /** @class */ (function () {
  62891. function SoundTrack(scene, options) {
  62892. this.id = -1;
  62893. this._isMainTrack = false;
  62894. this._isInitialized = false;
  62895. this._scene = scene;
  62896. this.soundCollection = new Array();
  62897. this._options = options;
  62898. if (!this._isMainTrack) {
  62899. this._scene.soundTracks.push(this);
  62900. this.id = this._scene.soundTracks.length - 1;
  62901. }
  62902. }
  62903. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62904. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62905. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62906. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62907. if (this._options) {
  62908. if (this._options.volume) {
  62909. this._outputAudioNode.gain.value = this._options.volume;
  62910. }
  62911. if (this._options.mainTrack) {
  62912. this._isMainTrack = this._options.mainTrack;
  62913. }
  62914. }
  62915. this._isInitialized = true;
  62916. }
  62917. };
  62918. SoundTrack.prototype.dispose = function () {
  62919. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62920. if (this._connectedAnalyser) {
  62921. this._connectedAnalyser.stopDebugCanvas();
  62922. }
  62923. while (this.soundCollection.length) {
  62924. this.soundCollection[0].dispose();
  62925. }
  62926. if (this._outputAudioNode) {
  62927. this._outputAudioNode.disconnect();
  62928. }
  62929. this._outputAudioNode = null;
  62930. }
  62931. };
  62932. SoundTrack.prototype.AddSound = function (sound) {
  62933. if (!this._isInitialized) {
  62934. this._initializeSoundTrackAudioGraph();
  62935. }
  62936. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62937. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62938. }
  62939. if (sound.soundTrackId) {
  62940. if (sound.soundTrackId === -1) {
  62941. this._scene.mainSoundTrack.RemoveSound(sound);
  62942. }
  62943. else {
  62944. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62945. }
  62946. }
  62947. this.soundCollection.push(sound);
  62948. sound.soundTrackId = this.id;
  62949. };
  62950. SoundTrack.prototype.RemoveSound = function (sound) {
  62951. var index = this.soundCollection.indexOf(sound);
  62952. if (index !== -1) {
  62953. this.soundCollection.splice(index, 1);
  62954. }
  62955. };
  62956. SoundTrack.prototype.setVolume = function (newVolume) {
  62957. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62958. this._outputAudioNode.gain.value = newVolume;
  62959. }
  62960. };
  62961. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62962. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62963. for (var i = 0; i < this.soundCollection.length; i++) {
  62964. this.soundCollection[i].switchPanningModelToHRTF();
  62965. }
  62966. }
  62967. };
  62968. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62970. for (var i = 0; i < this.soundCollection.length; i++) {
  62971. this.soundCollection[i].switchPanningModelToEqualPower();
  62972. }
  62973. }
  62974. };
  62975. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62976. if (this._connectedAnalyser) {
  62977. this._connectedAnalyser.stopDebugCanvas();
  62978. }
  62979. this._connectedAnalyser = analyser;
  62980. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62981. this._outputAudioNode.disconnect();
  62982. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62983. }
  62984. };
  62985. return SoundTrack;
  62986. }());
  62987. BABYLON.SoundTrack = SoundTrack;
  62988. })(BABYLON || (BABYLON = {}));
  62989. //# sourceMappingURL=babylon.soundtrack.js.map
  62990. var BABYLON;
  62991. (function (BABYLON) {
  62992. /**
  62993. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62994. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62995. */
  62996. var Analyser = /** @class */ (function () {
  62997. /**
  62998. * Creates a new analyser
  62999. * @param scene defines hosting scene
  63000. */
  63001. function Analyser(scene) {
  63002. /**
  63003. * Gets or sets the smoothing
  63004. * @ignorenaming
  63005. */
  63006. this.SMOOTHING = 0.75;
  63007. /**
  63008. * Gets or sets the FFT table size
  63009. * @ignorenaming
  63010. */
  63011. this.FFT_SIZE = 512;
  63012. /**
  63013. * Gets or sets the bar graph amplitude
  63014. * @ignorenaming
  63015. */
  63016. this.BARGRAPHAMPLITUDE = 256;
  63017. /**
  63018. * Gets or sets the position of the debug canvas
  63019. * @ignorenaming
  63020. */
  63021. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63022. /**
  63023. * Gets or sets the debug canvas size
  63024. * @ignorenaming
  63025. */
  63026. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63027. this._scene = scene;
  63028. this._audioEngine = BABYLON.Engine.audioEngine;
  63029. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63030. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63031. this._webAudioAnalyser.minDecibels = -140;
  63032. this._webAudioAnalyser.maxDecibels = 0;
  63033. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63034. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63035. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63036. }
  63037. }
  63038. /**
  63039. * Get the number of data values you will have to play with for the visualization
  63040. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63041. * @returns a number
  63042. */
  63043. Analyser.prototype.getFrequencyBinCount = function () {
  63044. if (this._audioEngine.canUseWebAudio) {
  63045. return this._webAudioAnalyser.frequencyBinCount;
  63046. }
  63047. else {
  63048. return 0;
  63049. }
  63050. };
  63051. /**
  63052. * Gets the current frequency data as a byte array
  63053. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63054. * @returns a Uint8Array
  63055. */
  63056. Analyser.prototype.getByteFrequencyData = function () {
  63057. if (this._audioEngine.canUseWebAudio) {
  63058. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63059. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63060. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63061. }
  63062. return this._byteFreqs;
  63063. };
  63064. /**
  63065. * Gets the current waveform as a byte array
  63066. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63067. * @returns a Uint8Array
  63068. */
  63069. Analyser.prototype.getByteTimeDomainData = function () {
  63070. if (this._audioEngine.canUseWebAudio) {
  63071. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63072. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63073. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63074. }
  63075. return this._byteTime;
  63076. };
  63077. /**
  63078. * Gets the current frequency data as a float array
  63079. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63080. * @returns a Float32Array
  63081. */
  63082. Analyser.prototype.getFloatFrequencyData = function () {
  63083. if (this._audioEngine.canUseWebAudio) {
  63084. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63085. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63086. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63087. }
  63088. return this._floatFreqs;
  63089. };
  63090. /**
  63091. * Renders the debug canvas
  63092. */
  63093. Analyser.prototype.drawDebugCanvas = function () {
  63094. var _this = this;
  63095. if (this._audioEngine.canUseWebAudio) {
  63096. if (!this._debugCanvas) {
  63097. this._debugCanvas = document.createElement("canvas");
  63098. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63099. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63100. this._debugCanvas.style.position = "absolute";
  63101. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63102. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63103. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63104. document.body.appendChild(this._debugCanvas);
  63105. this._registerFunc = function () {
  63106. _this.drawDebugCanvas();
  63107. };
  63108. this._scene.registerBeforeRender(this._registerFunc);
  63109. }
  63110. if (this._registerFunc && this._debugCanvasContext) {
  63111. var workingArray = this.getByteFrequencyData();
  63112. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63113. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63114. // Draw the frequency domain chart.
  63115. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63116. var value = workingArray[i];
  63117. var percent = value / this.BARGRAPHAMPLITUDE;
  63118. var height = this.DEBUGCANVASSIZE.height * percent;
  63119. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63120. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63121. var hue = i / this.getFrequencyBinCount() * 360;
  63122. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63123. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63124. }
  63125. }
  63126. }
  63127. };
  63128. /**
  63129. * Stops rendering the debug canvas and removes it
  63130. */
  63131. Analyser.prototype.stopDebugCanvas = function () {
  63132. if (this._debugCanvas) {
  63133. if (this._registerFunc) {
  63134. this._scene.unregisterBeforeRender(this._registerFunc);
  63135. this._registerFunc = null;
  63136. }
  63137. document.body.removeChild(this._debugCanvas);
  63138. this._debugCanvas = null;
  63139. this._debugCanvasContext = null;
  63140. }
  63141. };
  63142. /**
  63143. * Connects two audio nodes
  63144. * @param inputAudioNode defines first node to connect
  63145. * @param outputAudioNode defines second node to connect
  63146. */
  63147. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63148. if (this._audioEngine.canUseWebAudio) {
  63149. inputAudioNode.connect(this._webAudioAnalyser);
  63150. this._webAudioAnalyser.connect(outputAudioNode);
  63151. }
  63152. };
  63153. /**
  63154. * Releases all associated resources
  63155. */
  63156. Analyser.prototype.dispose = function () {
  63157. if (this._audioEngine.canUseWebAudio) {
  63158. this._webAudioAnalyser.disconnect();
  63159. }
  63160. };
  63161. return Analyser;
  63162. }());
  63163. BABYLON.Analyser = Analyser;
  63164. })(BABYLON || (BABYLON = {}));
  63165. //# sourceMappingURL=babylon.analyser.js.map
  63166. var BABYLON;
  63167. (function (BABYLON) {
  63168. var CubeTexture = /** @class */ (function (_super) {
  63169. __extends(CubeTexture, _super);
  63170. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63171. if (extensions === void 0) { extensions = null; }
  63172. if (noMipmap === void 0) { noMipmap = false; }
  63173. if (files === void 0) { files = null; }
  63174. if (onLoad === void 0) { onLoad = null; }
  63175. if (onError === void 0) { onError = null; }
  63176. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63177. if (prefiltered === void 0) { prefiltered = false; }
  63178. if (forcedExtension === void 0) { forcedExtension = null; }
  63179. var _this = _super.call(this, scene) || this;
  63180. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63181. /**
  63182. * Gets or sets the center of the bounding box associated with the cube texture
  63183. * It must define where the camera used to render the texture was set
  63184. */
  63185. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63186. _this._rotationY = 0;
  63187. _this.name = rootUrl;
  63188. _this.url = rootUrl;
  63189. _this._noMipmap = noMipmap;
  63190. _this.hasAlpha = false;
  63191. _this._format = format;
  63192. _this._prefiltered = prefiltered;
  63193. _this.isCube = true;
  63194. _this._textureMatrix = BABYLON.Matrix.Identity();
  63195. if (prefiltered) {
  63196. _this.gammaSpace = false;
  63197. }
  63198. if (!rootUrl && !files) {
  63199. return _this;
  63200. }
  63201. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63202. var lastDot = rootUrl.lastIndexOf(".");
  63203. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63204. var isDDS = (extension === ".dds");
  63205. if (!files) {
  63206. if (!isDDS && !extensions) {
  63207. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63208. }
  63209. files = [];
  63210. if (extensions) {
  63211. for (var index = 0; index < extensions.length; index++) {
  63212. files.push(rootUrl + extensions[index]);
  63213. }
  63214. }
  63215. }
  63216. _this._files = files;
  63217. if (!_this._texture) {
  63218. if (!scene.useDelayedTextureLoading) {
  63219. if (prefiltered) {
  63220. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63221. }
  63222. else {
  63223. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63224. }
  63225. }
  63226. else {
  63227. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63228. }
  63229. }
  63230. else if (onLoad) {
  63231. if (_this._texture.isReady) {
  63232. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63233. }
  63234. else {
  63235. _this._texture.onLoadedObservable.add(onLoad);
  63236. }
  63237. }
  63238. return _this;
  63239. }
  63240. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63241. get: function () {
  63242. return this._boundingBoxSize;
  63243. },
  63244. /**
  63245. * Gets or sets the size of the bounding box associated with the cube texture
  63246. * When defined, the cubemap will switch to local mode
  63247. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63248. * @example https://www.babylonjs-playground.com/#RNASML
  63249. */
  63250. set: function (value) {
  63251. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63252. return;
  63253. }
  63254. this._boundingBoxSize = value;
  63255. var scene = this.getScene();
  63256. if (scene) {
  63257. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63258. }
  63259. },
  63260. enumerable: true,
  63261. configurable: true
  63262. });
  63263. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63264. /**
  63265. * Gets texture matrix rotation angle around Y axis radians.
  63266. */
  63267. get: function () {
  63268. return this._rotationY;
  63269. },
  63270. /**
  63271. * Sets texture matrix rotation angle around Y axis in radians.
  63272. */
  63273. set: function (value) {
  63274. this._rotationY = value;
  63275. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63276. },
  63277. enumerable: true,
  63278. configurable: true
  63279. });
  63280. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63281. var rootUrlKey = "";
  63282. files.forEach(function (url) { return rootUrlKey += url; });
  63283. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63284. };
  63285. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63286. if (forcedExtension === void 0) { forcedExtension = null; }
  63287. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63288. };
  63289. // Methods
  63290. CubeTexture.prototype.delayLoad = function () {
  63291. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63292. return;
  63293. }
  63294. var scene = this.getScene();
  63295. if (!scene) {
  63296. return;
  63297. }
  63298. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63299. this._texture = this._getFromCache(this.url, this._noMipmap);
  63300. if (!this._texture) {
  63301. if (this._prefiltered) {
  63302. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63303. }
  63304. else {
  63305. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63306. }
  63307. }
  63308. };
  63309. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63310. return this._textureMatrix;
  63311. };
  63312. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63313. this._textureMatrix = value;
  63314. };
  63315. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63316. var texture = BABYLON.SerializationHelper.Parse(function () {
  63317. var prefiltered = false;
  63318. if (parsedTexture.prefiltered) {
  63319. prefiltered = parsedTexture.prefiltered;
  63320. }
  63321. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63322. }, parsedTexture, scene);
  63323. // Local Cubemaps
  63324. if (parsedTexture.boundingBoxPosition) {
  63325. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63326. }
  63327. if (parsedTexture.boundingBoxSize) {
  63328. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63329. }
  63330. // Animations
  63331. if (parsedTexture.animations) {
  63332. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63333. var parsedAnimation = parsedTexture.animations[animationIndex];
  63334. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63335. }
  63336. }
  63337. return texture;
  63338. };
  63339. CubeTexture.prototype.clone = function () {
  63340. var _this = this;
  63341. return BABYLON.SerializationHelper.Clone(function () {
  63342. var scene = _this.getScene();
  63343. if (!scene) {
  63344. return _this;
  63345. }
  63346. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63347. }, this);
  63348. };
  63349. __decorate([
  63350. BABYLON.serialize("rotationY")
  63351. ], CubeTexture.prototype, "_rotationY", void 0);
  63352. return CubeTexture;
  63353. }(BABYLON.BaseTexture));
  63354. BABYLON.CubeTexture = CubeTexture;
  63355. })(BABYLON || (BABYLON = {}));
  63356. //# sourceMappingURL=babylon.cubeTexture.js.map
  63357. var BABYLON;
  63358. (function (BABYLON) {
  63359. var RenderTargetTexture = /** @class */ (function (_super) {
  63360. __extends(RenderTargetTexture, _super);
  63361. /**
  63362. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63363. * or used a shadow, depth texture...
  63364. * @param name The friendly name of the texture
  63365. * @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)
  63366. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63367. * @param generateMipMaps True if mip maps need to be generated after render.
  63368. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63369. * @param type The type of the buffer in the RTT (int, half float, float...)
  63370. * @param isCube True if a cube texture needs to be created
  63371. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63372. * @param generateDepthBuffer True to generate a depth buffer
  63373. * @param generateStencilBuffer True to generate a stencil buffer
  63374. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63375. */
  63376. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63377. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63378. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63379. if (isCube === void 0) { isCube = false; }
  63380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63381. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63382. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63383. if (isMulti === void 0) { isMulti = false; }
  63384. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63385. _this.isCube = isCube;
  63386. /**
  63387. * Use this list to define the list of mesh you want to render.
  63388. */
  63389. _this.renderList = new Array();
  63390. _this.renderParticles = true;
  63391. _this.renderSprites = false;
  63392. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63393. _this.ignoreCameraViewport = false;
  63394. // Events
  63395. /**
  63396. * An event triggered when the texture is unbind.
  63397. */
  63398. _this.onBeforeBindObservable = new BABYLON.Observable();
  63399. /**
  63400. * An event triggered when the texture is unbind.
  63401. */
  63402. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63403. /**
  63404. * An event triggered before rendering the texture
  63405. */
  63406. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63407. /**
  63408. * An event triggered after rendering the texture
  63409. */
  63410. _this.onAfterRenderObservable = new BABYLON.Observable();
  63411. /**
  63412. * An event triggered after the texture clear
  63413. */
  63414. _this.onClearObservable = new BABYLON.Observable();
  63415. _this._currentRefreshId = -1;
  63416. _this._refreshRate = 1;
  63417. _this._samples = 1;
  63418. /**
  63419. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63420. * It must define where the camera used to render the texture is set
  63421. */
  63422. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63423. scene = _this.getScene();
  63424. if (!scene) {
  63425. return _this;
  63426. }
  63427. _this._engine = scene.getEngine();
  63428. _this.name = name;
  63429. _this.isRenderTarget = true;
  63430. _this._initialSizeParameter = size;
  63431. _this._processSizeParameter(size);
  63432. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63433. });
  63434. _this._generateMipMaps = generateMipMaps ? true : false;
  63435. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63436. // Rendering groups
  63437. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63438. if (isMulti) {
  63439. return _this;
  63440. }
  63441. _this._renderTargetOptions = {
  63442. generateMipMaps: generateMipMaps,
  63443. type: type,
  63444. samplingMode: samplingMode,
  63445. generateDepthBuffer: generateDepthBuffer,
  63446. generateStencilBuffer: generateStencilBuffer
  63447. };
  63448. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63449. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63450. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63451. }
  63452. if (isCube) {
  63453. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63454. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63455. _this._textureMatrix = BABYLON.Matrix.Identity();
  63456. }
  63457. else {
  63458. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63459. }
  63460. return _this;
  63461. }
  63462. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63463. get: function () {
  63464. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63465. },
  63466. enumerable: true,
  63467. configurable: true
  63468. });
  63469. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63470. get: function () {
  63471. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63472. },
  63473. enumerable: true,
  63474. configurable: true
  63475. });
  63476. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63477. get: function () {
  63478. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63479. },
  63480. enumerable: true,
  63481. configurable: true
  63482. });
  63483. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63484. set: function (callback) {
  63485. if (this._onAfterUnbindObserver) {
  63486. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63487. }
  63488. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63489. },
  63490. enumerable: true,
  63491. configurable: true
  63492. });
  63493. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63494. set: function (callback) {
  63495. if (this._onBeforeRenderObserver) {
  63496. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63497. }
  63498. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63499. },
  63500. enumerable: true,
  63501. configurable: true
  63502. });
  63503. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63504. set: function (callback) {
  63505. if (this._onAfterRenderObserver) {
  63506. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63507. }
  63508. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63509. },
  63510. enumerable: true,
  63511. configurable: true
  63512. });
  63513. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63514. set: function (callback) {
  63515. if (this._onClearObserver) {
  63516. this.onClearObservable.remove(this._onClearObserver);
  63517. }
  63518. this._onClearObserver = this.onClearObservable.add(callback);
  63519. },
  63520. enumerable: true,
  63521. configurable: true
  63522. });
  63523. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63524. get: function () {
  63525. return this._renderTargetOptions;
  63526. },
  63527. enumerable: true,
  63528. configurable: true
  63529. });
  63530. RenderTargetTexture.prototype._onRatioRescale = function () {
  63531. if (this._sizeRatio) {
  63532. this.resize(this._initialSizeParameter);
  63533. }
  63534. };
  63535. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63536. get: function () {
  63537. return this._boundingBoxSize;
  63538. },
  63539. /**
  63540. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63541. * When defined, the cubemap will switch to local mode
  63542. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63543. * @example https://www.babylonjs-playground.com/#RNASML
  63544. */
  63545. set: function (value) {
  63546. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63547. return;
  63548. }
  63549. this._boundingBoxSize = value;
  63550. var scene = this.getScene();
  63551. if (scene) {
  63552. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63553. }
  63554. },
  63555. enumerable: true,
  63556. configurable: true
  63557. });
  63558. /**
  63559. * Creates a depth stencil texture.
  63560. * This is only available in WebGL 2 or with the depth texture extension available.
  63561. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63562. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63563. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63564. */
  63565. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63566. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63567. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63568. if (generateStencil === void 0) { generateStencil = false; }
  63569. if (!this.getScene()) {
  63570. return;
  63571. }
  63572. var engine = this.getScene().getEngine();
  63573. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63574. bilinearFiltering: bilinearFiltering,
  63575. comparisonFunction: comparisonFunction,
  63576. generateStencil: generateStencil,
  63577. isCube: this.isCube
  63578. });
  63579. engine.setFrameBufferDepthStencilTexture(this);
  63580. };
  63581. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63582. if (size.ratio) {
  63583. this._sizeRatio = size.ratio;
  63584. this._size = {
  63585. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63586. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63587. };
  63588. }
  63589. else {
  63590. this._size = size;
  63591. }
  63592. };
  63593. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63594. get: function () {
  63595. return this._samples;
  63596. },
  63597. set: function (value) {
  63598. if (this._samples === value) {
  63599. return;
  63600. }
  63601. var scene = this.getScene();
  63602. if (!scene) {
  63603. return;
  63604. }
  63605. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63606. },
  63607. enumerable: true,
  63608. configurable: true
  63609. });
  63610. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63611. this._currentRefreshId = -1;
  63612. };
  63613. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63614. get: function () {
  63615. return this._refreshRate;
  63616. },
  63617. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63618. set: function (value) {
  63619. this._refreshRate = value;
  63620. this.resetRefreshCounter();
  63621. },
  63622. enumerable: true,
  63623. configurable: true
  63624. });
  63625. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63626. if (!this._postProcessManager) {
  63627. var scene = this.getScene();
  63628. if (!scene) {
  63629. return;
  63630. }
  63631. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63632. this._postProcesses = new Array();
  63633. }
  63634. this._postProcesses.push(postProcess);
  63635. this._postProcesses[0].autoClear = false;
  63636. };
  63637. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63638. if (!this._postProcesses) {
  63639. return;
  63640. }
  63641. if (dispose) {
  63642. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63643. var postProcess = _a[_i];
  63644. postProcess.dispose();
  63645. }
  63646. }
  63647. this._postProcesses = [];
  63648. };
  63649. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63650. if (!this._postProcesses) {
  63651. return;
  63652. }
  63653. var index = this._postProcesses.indexOf(postProcess);
  63654. if (index === -1) {
  63655. return;
  63656. }
  63657. this._postProcesses.splice(index, 1);
  63658. if (this._postProcesses.length > 0) {
  63659. this._postProcesses[0].autoClear = false;
  63660. }
  63661. };
  63662. RenderTargetTexture.prototype._shouldRender = function () {
  63663. if (this._currentRefreshId === -1) { // At least render once
  63664. this._currentRefreshId = 1;
  63665. return true;
  63666. }
  63667. if (this.refreshRate === this._currentRefreshId) {
  63668. this._currentRefreshId = 1;
  63669. return true;
  63670. }
  63671. this._currentRefreshId++;
  63672. return false;
  63673. };
  63674. RenderTargetTexture.prototype.getRenderSize = function () {
  63675. if (this._size.width) {
  63676. return this._size.width;
  63677. }
  63678. return this._size;
  63679. };
  63680. RenderTargetTexture.prototype.getRenderWidth = function () {
  63681. if (this._size.width) {
  63682. return this._size.width;
  63683. }
  63684. return this._size;
  63685. };
  63686. RenderTargetTexture.prototype.getRenderHeight = function () {
  63687. if (this._size.width) {
  63688. return this._size.height;
  63689. }
  63690. return this._size;
  63691. };
  63692. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63693. get: function () {
  63694. return true;
  63695. },
  63696. enumerable: true,
  63697. configurable: true
  63698. });
  63699. RenderTargetTexture.prototype.scale = function (ratio) {
  63700. var newSize = this.getRenderSize() * ratio;
  63701. this.resize(newSize);
  63702. };
  63703. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63704. if (this.isCube) {
  63705. return this._textureMatrix;
  63706. }
  63707. return _super.prototype.getReflectionTextureMatrix.call(this);
  63708. };
  63709. RenderTargetTexture.prototype.resize = function (size) {
  63710. this.releaseInternalTexture();
  63711. var scene = this.getScene();
  63712. if (!scene) {
  63713. return;
  63714. }
  63715. this._processSizeParameter(size);
  63716. if (this.isCube) {
  63717. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63718. }
  63719. else {
  63720. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63721. }
  63722. };
  63723. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63724. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63725. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63726. var scene = this.getScene();
  63727. if (!scene) {
  63728. return;
  63729. }
  63730. var engine = scene.getEngine();
  63731. if (this.useCameraPostProcesses !== undefined) {
  63732. useCameraPostProcess = this.useCameraPostProcesses;
  63733. }
  63734. if (this._waitingRenderList) {
  63735. this.renderList = [];
  63736. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63737. var id = this._waitingRenderList[index];
  63738. var mesh_1 = scene.getMeshByID(id);
  63739. if (mesh_1) {
  63740. this.renderList.push(mesh_1);
  63741. }
  63742. }
  63743. delete this._waitingRenderList;
  63744. }
  63745. // Is predicate defined?
  63746. if (this.renderListPredicate) {
  63747. if (this.renderList) {
  63748. this.renderList.splice(0); // Clear previous renderList
  63749. }
  63750. else {
  63751. this.renderList = [];
  63752. }
  63753. var scene = this.getScene();
  63754. if (!scene) {
  63755. return;
  63756. }
  63757. var sceneMeshes = scene.meshes;
  63758. for (var index = 0; index < sceneMeshes.length; index++) {
  63759. var mesh = sceneMeshes[index];
  63760. if (this.renderListPredicate(mesh)) {
  63761. this.renderList.push(mesh);
  63762. }
  63763. }
  63764. }
  63765. this.onBeforeBindObservable.notifyObservers(this);
  63766. // Set custom projection.
  63767. // Needs to be before binding to prevent changing the aspect ratio.
  63768. var camera;
  63769. if (this.activeCamera) {
  63770. camera = this.activeCamera;
  63771. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63772. if (this.activeCamera !== scene.activeCamera) {
  63773. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63774. }
  63775. }
  63776. else {
  63777. camera = scene.activeCamera;
  63778. if (camera) {
  63779. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63780. }
  63781. }
  63782. // Prepare renderingManager
  63783. this._renderingManager.reset();
  63784. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63785. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63786. var sceneRenderId = scene.getRenderId();
  63787. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63788. var mesh = currentRenderList[meshIndex];
  63789. if (mesh) {
  63790. if (!mesh.isReady(this.refreshRate === 0)) {
  63791. this.resetRefreshCounter();
  63792. continue;
  63793. }
  63794. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63795. var isMasked = void 0;
  63796. if (!this.renderList && camera) {
  63797. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63798. }
  63799. else {
  63800. isMasked = false;
  63801. }
  63802. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63803. mesh._activate(sceneRenderId);
  63804. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63805. var subMesh = mesh.subMeshes[subIndex];
  63806. scene._activeIndices.addCount(subMesh.indexCount, false);
  63807. this._renderingManager.dispatch(subMesh, mesh);
  63808. }
  63809. }
  63810. }
  63811. }
  63812. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63813. var particleSystem = scene.particleSystems[particleIndex];
  63814. var emitter = particleSystem.emitter;
  63815. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63816. continue;
  63817. }
  63818. if (currentRenderList.indexOf(emitter) >= 0) {
  63819. this._renderingManager.dispatchParticles(particleSystem);
  63820. }
  63821. }
  63822. if (this.isCube) {
  63823. for (var face = 0; face < 6; face++) {
  63824. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63825. scene.incrementRenderId();
  63826. scene.resetCachedMaterial();
  63827. }
  63828. }
  63829. else {
  63830. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63831. }
  63832. this.onAfterUnbindObservable.notifyObservers(this);
  63833. if (scene.activeCamera) {
  63834. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63835. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63836. }
  63837. engine.setViewport(scene.activeCamera.viewport);
  63838. }
  63839. scene.resetCachedMaterial();
  63840. };
  63841. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63842. var minimum = 128;
  63843. var x = renderDimension * scale;
  63844. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63845. // Ensure we don't exceed the render dimension (while staying POT)
  63846. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63847. };
  63848. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63849. var _this = this;
  63850. if (!this._texture) {
  63851. return;
  63852. }
  63853. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63854. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63855. });
  63856. };
  63857. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63858. var scene = this.getScene();
  63859. if (!scene) {
  63860. return;
  63861. }
  63862. var engine = scene.getEngine();
  63863. if (!this._texture) {
  63864. return;
  63865. }
  63866. // Bind
  63867. if (this._postProcessManager) {
  63868. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63869. }
  63870. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63871. if (this._texture) {
  63872. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63873. }
  63874. }
  63875. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63876. // Clear
  63877. if (this.onClearObservable.hasObservers()) {
  63878. this.onClearObservable.notifyObservers(engine);
  63879. }
  63880. else {
  63881. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63882. }
  63883. if (!this._doNotChangeAspectRatio) {
  63884. scene.updateTransformMatrix(true);
  63885. }
  63886. // Render
  63887. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63888. if (this._postProcessManager) {
  63889. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63890. }
  63891. else if (useCameraPostProcess) {
  63892. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63893. }
  63894. if (!this._doNotChangeAspectRatio) {
  63895. scene.updateTransformMatrix(true);
  63896. }
  63897. // Dump ?
  63898. if (dumpForDebug) {
  63899. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63900. }
  63901. // Unbind
  63902. if (!this.isCube || faceIndex === 5) {
  63903. if (this.isCube) {
  63904. if (faceIndex === 5) {
  63905. engine.generateMipMapsForCubemap(this._texture);
  63906. }
  63907. }
  63908. this.unbindFrameBuffer(engine, faceIndex);
  63909. }
  63910. else {
  63911. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63912. }
  63913. };
  63914. /**
  63915. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63916. * This allowed control for front to back rendering or reversly depending of the special needs.
  63917. *
  63918. * @param renderingGroupId The rendering group id corresponding to its index
  63919. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63920. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63921. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63922. */
  63923. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63924. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63925. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63926. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63927. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63928. };
  63929. /**
  63930. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63931. *
  63932. * @param renderingGroupId The rendering group id corresponding to its index
  63933. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63934. */
  63935. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63936. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63937. };
  63938. RenderTargetTexture.prototype.clone = function () {
  63939. var textureSize = this.getSize();
  63940. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63941. // Base texture
  63942. newTexture.hasAlpha = this.hasAlpha;
  63943. newTexture.level = this.level;
  63944. // RenderTarget Texture
  63945. newTexture.coordinatesMode = this.coordinatesMode;
  63946. if (this.renderList) {
  63947. newTexture.renderList = this.renderList.slice(0);
  63948. }
  63949. return newTexture;
  63950. };
  63951. RenderTargetTexture.prototype.serialize = function () {
  63952. if (!this.name) {
  63953. return null;
  63954. }
  63955. var serializationObject = _super.prototype.serialize.call(this);
  63956. serializationObject.renderTargetSize = this.getRenderSize();
  63957. serializationObject.renderList = [];
  63958. if (this.renderList) {
  63959. for (var index = 0; index < this.renderList.length; index++) {
  63960. serializationObject.renderList.push(this.renderList[index].id);
  63961. }
  63962. }
  63963. return serializationObject;
  63964. };
  63965. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63966. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63967. var objBuffer = this.getInternalTexture();
  63968. var scene = this.getScene();
  63969. if (objBuffer && scene) {
  63970. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63971. }
  63972. };
  63973. RenderTargetTexture.prototype.dispose = function () {
  63974. if (this._postProcessManager) {
  63975. this._postProcessManager.dispose();
  63976. this._postProcessManager = null;
  63977. }
  63978. this.clearPostProcesses(true);
  63979. if (this._resizeObserver) {
  63980. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63981. this._resizeObserver = null;
  63982. }
  63983. this.renderList = null;
  63984. // Remove from custom render targets
  63985. var scene = this.getScene();
  63986. if (!scene) {
  63987. return;
  63988. }
  63989. var index = scene.customRenderTargets.indexOf(this);
  63990. if (index >= 0) {
  63991. scene.customRenderTargets.splice(index, 1);
  63992. }
  63993. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63994. var camera = _a[_i];
  63995. index = camera.customRenderTargets.indexOf(this);
  63996. if (index >= 0) {
  63997. camera.customRenderTargets.splice(index, 1);
  63998. }
  63999. }
  64000. _super.prototype.dispose.call(this);
  64001. };
  64002. RenderTargetTexture.prototype._rebuild = function () {
  64003. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64004. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64005. }
  64006. if (this._postProcessManager) {
  64007. this._postProcessManager._rebuild();
  64008. }
  64009. };
  64010. /**
  64011. * Clear the info related to rendering groups preventing retention point in material dispose.
  64012. */
  64013. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64014. if (this._renderingManager) {
  64015. this._renderingManager.freeRenderingGroups();
  64016. }
  64017. };
  64018. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64019. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64020. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64021. return RenderTargetTexture;
  64022. }(BABYLON.Texture));
  64023. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64024. })(BABYLON || (BABYLON = {}));
  64025. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64026. var BABYLON;
  64027. (function (BABYLON) {
  64028. ;
  64029. var MultiRenderTarget = /** @class */ (function (_super) {
  64030. __extends(MultiRenderTarget, _super);
  64031. function MultiRenderTarget(name, size, count, scene, options) {
  64032. var _this = this;
  64033. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64034. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64035. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64036. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64037. _this._engine = scene.getEngine();
  64038. if (!_this.isSupported) {
  64039. _this.dispose();
  64040. return;
  64041. }
  64042. var types = [];
  64043. var samplingModes = [];
  64044. for (var i = 0; i < count; i++) {
  64045. if (options && options.types && options.types[i] !== undefined) {
  64046. types.push(options.types[i]);
  64047. }
  64048. else {
  64049. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64050. }
  64051. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64052. samplingModes.push(options.samplingModes[i]);
  64053. }
  64054. else {
  64055. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64056. }
  64057. }
  64058. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64059. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64060. _this._size = size;
  64061. _this._multiRenderTargetOptions = {
  64062. samplingModes: samplingModes,
  64063. generateMipMaps: generateMipMaps,
  64064. generateDepthBuffer: generateDepthBuffer,
  64065. generateStencilBuffer: generateStencilBuffer,
  64066. generateDepthTexture: generateDepthTexture,
  64067. types: types,
  64068. textureCount: count
  64069. };
  64070. _this._createInternalTextures();
  64071. _this._createTextures();
  64072. return _this;
  64073. }
  64074. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64075. get: function () {
  64076. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64077. },
  64078. enumerable: true,
  64079. configurable: true
  64080. });
  64081. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64082. get: function () {
  64083. return this._textures;
  64084. },
  64085. enumerable: true,
  64086. configurable: true
  64087. });
  64088. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64089. get: function () {
  64090. return this._textures[this._textures.length - 1];
  64091. },
  64092. enumerable: true,
  64093. configurable: true
  64094. });
  64095. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64096. set: function (wrap) {
  64097. if (this._textures) {
  64098. for (var i = 0; i < this._textures.length; i++) {
  64099. this._textures[i].wrapU = wrap;
  64100. }
  64101. }
  64102. },
  64103. enumerable: true,
  64104. configurable: true
  64105. });
  64106. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64107. set: function (wrap) {
  64108. if (this._textures) {
  64109. for (var i = 0; i < this._textures.length; i++) {
  64110. this._textures[i].wrapV = wrap;
  64111. }
  64112. }
  64113. },
  64114. enumerable: true,
  64115. configurable: true
  64116. });
  64117. MultiRenderTarget.prototype._rebuild = function () {
  64118. this.releaseInternalTextures();
  64119. this._createInternalTextures();
  64120. for (var i = 0; i < this._internalTextures.length; i++) {
  64121. var texture = this._textures[i];
  64122. texture._texture = this._internalTextures[i];
  64123. }
  64124. // Keeps references to frame buffer and stencil/depth buffer
  64125. this._texture = this._internalTextures[0];
  64126. };
  64127. MultiRenderTarget.prototype._createInternalTextures = function () {
  64128. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64129. };
  64130. MultiRenderTarget.prototype._createTextures = function () {
  64131. this._textures = [];
  64132. for (var i = 0; i < this._internalTextures.length; i++) {
  64133. var texture = new BABYLON.Texture(null, this.getScene());
  64134. texture._texture = this._internalTextures[i];
  64135. this._textures.push(texture);
  64136. }
  64137. // Keeps references to frame buffer and stencil/depth buffer
  64138. this._texture = this._internalTextures[0];
  64139. };
  64140. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64141. get: function () {
  64142. return this._samples;
  64143. },
  64144. set: function (value) {
  64145. if (this._samples === value) {
  64146. return;
  64147. }
  64148. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64149. },
  64150. enumerable: true,
  64151. configurable: true
  64152. });
  64153. MultiRenderTarget.prototype.resize = function (size) {
  64154. this.releaseInternalTextures();
  64155. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64156. this._createInternalTextures();
  64157. };
  64158. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64159. var _this = this;
  64160. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64161. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64162. });
  64163. };
  64164. MultiRenderTarget.prototype.dispose = function () {
  64165. this.releaseInternalTextures();
  64166. _super.prototype.dispose.call(this);
  64167. };
  64168. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64169. if (!this._internalTextures) {
  64170. return;
  64171. }
  64172. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64173. if (this._internalTextures[i] !== undefined) {
  64174. this._internalTextures[i].dispose();
  64175. this._internalTextures.splice(i, 1);
  64176. }
  64177. }
  64178. };
  64179. return MultiRenderTarget;
  64180. }(BABYLON.RenderTargetTexture));
  64181. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64182. })(BABYLON || (BABYLON = {}));
  64183. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64184. var BABYLON;
  64185. (function (BABYLON) {
  64186. var MirrorTexture = /** @class */ (function (_super) {
  64187. __extends(MirrorTexture, _super);
  64188. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64189. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64191. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64192. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64193. _this.scene = scene;
  64194. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64195. _this._transformMatrix = BABYLON.Matrix.Zero();
  64196. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64197. _this._adaptiveBlurKernel = 0;
  64198. _this._blurKernelX = 0;
  64199. _this._blurKernelY = 0;
  64200. _this._blurRatio = 1.0;
  64201. _this.ignoreCameraViewport = true;
  64202. _this._updateGammaSpace();
  64203. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64204. _this._updateGammaSpace;
  64205. });
  64206. _this.onBeforeRenderObservable.add(function () {
  64207. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64208. _this._savedViewMatrix = scene.getViewMatrix();
  64209. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64210. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64211. scene.clipPlane = _this.mirrorPlane;
  64212. scene.getEngine().cullBackFaces = false;
  64213. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64214. });
  64215. _this.onAfterRenderObservable.add(function () {
  64216. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64217. scene.getEngine().cullBackFaces = true;
  64218. scene._mirroredCameraPosition = null;
  64219. delete scene.clipPlane;
  64220. });
  64221. return _this;
  64222. }
  64223. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64224. get: function () {
  64225. return this._blurRatio;
  64226. },
  64227. set: function (value) {
  64228. if (this._blurRatio === value) {
  64229. return;
  64230. }
  64231. this._blurRatio = value;
  64232. this._preparePostProcesses();
  64233. },
  64234. enumerable: true,
  64235. configurable: true
  64236. });
  64237. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64238. set: function (value) {
  64239. this._adaptiveBlurKernel = value;
  64240. this._autoComputeBlurKernel();
  64241. },
  64242. enumerable: true,
  64243. configurable: true
  64244. });
  64245. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64246. set: function (value) {
  64247. this.blurKernelX = value;
  64248. this.blurKernelY = value;
  64249. },
  64250. enumerable: true,
  64251. configurable: true
  64252. });
  64253. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64254. get: function () {
  64255. return this._blurKernelX;
  64256. },
  64257. set: function (value) {
  64258. if (this._blurKernelX === value) {
  64259. return;
  64260. }
  64261. this._blurKernelX = value;
  64262. this._preparePostProcesses();
  64263. },
  64264. enumerable: true,
  64265. configurable: true
  64266. });
  64267. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64268. get: function () {
  64269. return this._blurKernelY;
  64270. },
  64271. set: function (value) {
  64272. if (this._blurKernelY === value) {
  64273. return;
  64274. }
  64275. this._blurKernelY = value;
  64276. this._preparePostProcesses();
  64277. },
  64278. enumerable: true,
  64279. configurable: true
  64280. });
  64281. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64282. var engine = this.getScene().getEngine();
  64283. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64284. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64285. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64286. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64287. };
  64288. MirrorTexture.prototype._onRatioRescale = function () {
  64289. if (this._sizeRatio) {
  64290. this.resize(this._initialSizeParameter);
  64291. if (!this._adaptiveBlurKernel) {
  64292. this._preparePostProcesses();
  64293. }
  64294. }
  64295. if (this._adaptiveBlurKernel) {
  64296. this._autoComputeBlurKernel();
  64297. }
  64298. };
  64299. MirrorTexture.prototype._updateGammaSpace = function () {
  64300. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64301. };
  64302. MirrorTexture.prototype._preparePostProcesses = function () {
  64303. this.clearPostProcesses(true);
  64304. if (this._blurKernelX && this._blurKernelY) {
  64305. var engine = this.getScene().getEngine();
  64306. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64307. 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);
  64308. this._blurX.autoClear = false;
  64309. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64310. this._blurX.inputTexture = this._texture;
  64311. }
  64312. else {
  64313. this._blurX.alwaysForcePOT = true;
  64314. }
  64315. 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);
  64316. this._blurY.autoClear = false;
  64317. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64318. this.addPostProcess(this._blurX);
  64319. this.addPostProcess(this._blurY);
  64320. }
  64321. else {
  64322. if (this._blurY) {
  64323. this.removePostProcess(this._blurY);
  64324. this._blurY.dispose();
  64325. this._blurY = null;
  64326. }
  64327. if (this._blurX) {
  64328. this.removePostProcess(this._blurX);
  64329. this._blurX.dispose();
  64330. this._blurX = null;
  64331. }
  64332. }
  64333. };
  64334. MirrorTexture.prototype.clone = function () {
  64335. var scene = this.getScene();
  64336. if (!scene) {
  64337. return this;
  64338. }
  64339. var textureSize = this.getSize();
  64340. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64341. // Base texture
  64342. newTexture.hasAlpha = this.hasAlpha;
  64343. newTexture.level = this.level;
  64344. // Mirror Texture
  64345. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64346. if (this.renderList) {
  64347. newTexture.renderList = this.renderList.slice(0);
  64348. }
  64349. return newTexture;
  64350. };
  64351. MirrorTexture.prototype.serialize = function () {
  64352. if (!this.name) {
  64353. return null;
  64354. }
  64355. var serializationObject = _super.prototype.serialize.call(this);
  64356. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64357. return serializationObject;
  64358. };
  64359. MirrorTexture.prototype.dispose = function () {
  64360. _super.prototype.dispose.call(this);
  64361. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64362. };
  64363. return MirrorTexture;
  64364. }(BABYLON.RenderTargetTexture));
  64365. BABYLON.MirrorTexture = MirrorTexture;
  64366. })(BABYLON || (BABYLON = {}));
  64367. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64368. var BABYLON;
  64369. (function (BABYLON) {
  64370. /**
  64371. * Creates a refraction texture used by refraction channel of the standard material.
  64372. * @param name the texture name
  64373. * @param size size of the underlying texture
  64374. * @param scene root scene
  64375. */
  64376. var RefractionTexture = /** @class */ (function (_super) {
  64377. __extends(RefractionTexture, _super);
  64378. function RefractionTexture(name, size, scene, generateMipMaps) {
  64379. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64380. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64381. _this.depth = 2.0;
  64382. _this.onBeforeRenderObservable.add(function () {
  64383. scene.clipPlane = _this.refractionPlane;
  64384. });
  64385. _this.onAfterRenderObservable.add(function () {
  64386. delete scene.clipPlane;
  64387. });
  64388. return _this;
  64389. }
  64390. RefractionTexture.prototype.clone = function () {
  64391. var scene = this.getScene();
  64392. if (!scene) {
  64393. return this;
  64394. }
  64395. var textureSize = this.getSize();
  64396. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64397. // Base texture
  64398. newTexture.hasAlpha = this.hasAlpha;
  64399. newTexture.level = this.level;
  64400. // Refraction Texture
  64401. newTexture.refractionPlane = this.refractionPlane.clone();
  64402. if (this.renderList) {
  64403. newTexture.renderList = this.renderList.slice(0);
  64404. }
  64405. newTexture.depth = this.depth;
  64406. return newTexture;
  64407. };
  64408. RefractionTexture.prototype.serialize = function () {
  64409. if (!this.name) {
  64410. return null;
  64411. }
  64412. var serializationObject = _super.prototype.serialize.call(this);
  64413. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64414. serializationObject.depth = this.depth;
  64415. return serializationObject;
  64416. };
  64417. return RefractionTexture;
  64418. }(BABYLON.RenderTargetTexture));
  64419. BABYLON.RefractionTexture = RefractionTexture;
  64420. })(BABYLON || (BABYLON = {}));
  64421. //# sourceMappingURL=babylon.refractionTexture.js.map
  64422. var BABYLON;
  64423. (function (BABYLON) {
  64424. /**
  64425. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64426. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64427. */
  64428. var DynamicTexture = /** @class */ (function (_super) {
  64429. __extends(DynamicTexture, _super);
  64430. /**
  64431. * Creates a {BABYLON.DynamicTexture}
  64432. * @param name defines the name of the texture
  64433. * @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
  64434. * @param scene defines the scene where you want the texture
  64435. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64436. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64437. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64438. */
  64439. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64440. if (scene === void 0) { scene = null; }
  64441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64442. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64443. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64444. _this.name = name;
  64445. _this._engine = _this.getScene().getEngine();
  64446. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64447. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64448. _this._generateMipMaps = generateMipMaps;
  64449. if (options.getContext) {
  64450. _this._canvas = options;
  64451. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64452. }
  64453. else {
  64454. _this._canvas = document.createElement("canvas");
  64455. if (options.width || options.width === 0) {
  64456. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64457. }
  64458. else {
  64459. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64460. }
  64461. }
  64462. var textureSize = _this.getSize();
  64463. _this._canvas.width = textureSize.width;
  64464. _this._canvas.height = textureSize.height;
  64465. _this._context = _this._canvas.getContext("2d");
  64466. return _this;
  64467. }
  64468. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64469. /**
  64470. * Gets the current state of canRescale
  64471. */
  64472. get: function () {
  64473. return true;
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. DynamicTexture.prototype._recreate = function (textureSize) {
  64479. this._canvas.width = textureSize.width;
  64480. this._canvas.height = textureSize.height;
  64481. this.releaseInternalTexture();
  64482. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64483. };
  64484. /**
  64485. * Scales the texture
  64486. * @param ratio the scale factor to apply to both width and height
  64487. */
  64488. DynamicTexture.prototype.scale = function (ratio) {
  64489. var textureSize = this.getSize();
  64490. textureSize.width *= ratio;
  64491. textureSize.height *= ratio;
  64492. this._recreate(textureSize);
  64493. };
  64494. /**
  64495. * Resizes the texture
  64496. * @param width the new width
  64497. * @param height the new height
  64498. */
  64499. DynamicTexture.prototype.scaleTo = function (width, height) {
  64500. var textureSize = this.getSize();
  64501. textureSize.width = width;
  64502. textureSize.height = height;
  64503. this._recreate(textureSize);
  64504. };
  64505. /**
  64506. * Gets the context of the canvas used by the texture
  64507. * @returns the canvas context of the dynamic texture
  64508. */
  64509. DynamicTexture.prototype.getContext = function () {
  64510. return this._context;
  64511. };
  64512. /**
  64513. * Clears the texture
  64514. */
  64515. DynamicTexture.prototype.clear = function () {
  64516. var size = this.getSize();
  64517. this._context.fillRect(0, 0, size.width, size.height);
  64518. };
  64519. /**
  64520. * Updates the texture
  64521. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64522. */
  64523. DynamicTexture.prototype.update = function (invertY) {
  64524. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64525. };
  64526. /**
  64527. * Draws text onto the texture
  64528. * @param text defines the text to be drawn
  64529. * @param x defines the placement of the text from the left
  64530. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64531. * @param font defines the font to be used with font-style, font-size, font-name
  64532. * @param color defines the color used for the text
  64533. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64534. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64535. * @param update defines whether texture is immediately update (default is true)
  64536. */
  64537. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64538. if (update === void 0) { update = true; }
  64539. var size = this.getSize();
  64540. if (clearColor) {
  64541. this._context.fillStyle = clearColor;
  64542. this._context.fillRect(0, 0, size.width, size.height);
  64543. }
  64544. this._context.font = font;
  64545. if (x === null || x === undefined) {
  64546. var textSize = this._context.measureText(text);
  64547. x = (size.width - textSize.width) / 2;
  64548. }
  64549. if (y === null || y === undefined) {
  64550. var fontSize = parseInt((font.replace(/\D/g, '')));
  64551. y = (size.height / 2) + (fontSize / 3.65);
  64552. }
  64553. this._context.fillStyle = color;
  64554. this._context.fillText(text, x, y);
  64555. if (update) {
  64556. this.update(invertY);
  64557. }
  64558. };
  64559. /**
  64560. * Clones the texture
  64561. * @returns the clone of the texture.
  64562. */
  64563. DynamicTexture.prototype.clone = function () {
  64564. var scene = this.getScene();
  64565. if (!scene) {
  64566. return this;
  64567. }
  64568. var textureSize = this.getSize();
  64569. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64570. // Base texture
  64571. newTexture.hasAlpha = this.hasAlpha;
  64572. newTexture.level = this.level;
  64573. // Dynamic Texture
  64574. newTexture.wrapU = this.wrapU;
  64575. newTexture.wrapV = this.wrapV;
  64576. return newTexture;
  64577. };
  64578. /** @hidden */
  64579. DynamicTexture.prototype._rebuild = function () {
  64580. this.update();
  64581. };
  64582. return DynamicTexture;
  64583. }(BABYLON.Texture));
  64584. BABYLON.DynamicTexture = DynamicTexture;
  64585. })(BABYLON || (BABYLON = {}));
  64586. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64587. var BABYLON;
  64588. (function (BABYLON) {
  64589. var VideoTexture = /** @class */ (function (_super) {
  64590. __extends(VideoTexture, _super);
  64591. /**
  64592. * Creates a video texture.
  64593. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64594. * @param {string | null} name optional name, will detect from video source, if not defined
  64595. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64596. * @param {BABYLON.Scene} scene is obviously the current scene.
  64597. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64598. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64599. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64600. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64601. */
  64602. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64603. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64604. if (invertY === void 0) { invertY = false; }
  64605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64606. if (settings === void 0) { settings = {
  64607. autoPlay: true,
  64608. loop: true,
  64609. autoUpdateTexture: true,
  64610. }; }
  64611. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64612. _this._stillImageCaptured = false;
  64613. _this._createInternalTexture = function () {
  64614. if (_this._texture != null) {
  64615. return;
  64616. }
  64617. if (!_this._engine.needPOTTextures ||
  64618. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64619. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64620. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64621. }
  64622. else {
  64623. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64624. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64625. _this._generateMipMaps = false;
  64626. }
  64627. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64628. if (!_this.video.autoplay) {
  64629. var oldHandler_1 = _this.video.onplaying;
  64630. _this.video.onplaying = function () {
  64631. _this.video.onplaying = oldHandler_1;
  64632. _this._texture.isReady = true;
  64633. _this._updateInternalTexture();
  64634. _this.video.pause();
  64635. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64636. _this.onLoadObservable.notifyObservers(_this);
  64637. }
  64638. };
  64639. _this.video.play();
  64640. }
  64641. else {
  64642. _this._texture.isReady = true;
  64643. _this._updateInternalTexture();
  64644. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64645. _this.onLoadObservable.notifyObservers(_this);
  64646. }
  64647. }
  64648. };
  64649. _this.reset = function () {
  64650. if (_this._texture == null) {
  64651. return;
  64652. }
  64653. _this._texture.dispose();
  64654. _this._texture = null;
  64655. };
  64656. _this._updateInternalTexture = function (e) {
  64657. if (_this._texture == null || !_this._texture.isReady) {
  64658. return;
  64659. }
  64660. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64661. return;
  64662. }
  64663. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64664. };
  64665. _this._engine = _this.getScene().getEngine();
  64666. _this._generateMipMaps = generateMipMaps;
  64667. _this._samplingMode = samplingMode;
  64668. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64669. _this.name = name || _this._getName(src);
  64670. _this.video = _this._getVideo(src);
  64671. if (settings.autoPlay !== undefined) {
  64672. _this.video.autoplay = settings.autoPlay;
  64673. }
  64674. if (settings.loop !== undefined) {
  64675. _this.video.loop = settings.loop;
  64676. }
  64677. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64678. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64679. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64680. _this.video.addEventListener("emptied", _this.reset);
  64681. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64682. _this._createInternalTexture();
  64683. }
  64684. return _this;
  64685. }
  64686. VideoTexture.prototype._getName = function (src) {
  64687. if (src instanceof HTMLVideoElement) {
  64688. return src.currentSrc;
  64689. }
  64690. if (typeof src === "object") {
  64691. return src.toString();
  64692. }
  64693. return src;
  64694. };
  64695. ;
  64696. VideoTexture.prototype._getVideo = function (src) {
  64697. if (src instanceof HTMLVideoElement) {
  64698. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64699. return src;
  64700. }
  64701. var video = document.createElement("video");
  64702. if (typeof src === "string") {
  64703. BABYLON.Tools.SetCorsBehavior(src, video);
  64704. video.src = src;
  64705. }
  64706. else {
  64707. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64708. src.forEach(function (url) {
  64709. var source = document.createElement("source");
  64710. source.src = url;
  64711. video.appendChild(source);
  64712. });
  64713. }
  64714. return video;
  64715. };
  64716. ;
  64717. /**
  64718. * Internal method to initiate `update`.
  64719. */
  64720. VideoTexture.prototype._rebuild = function () {
  64721. this.update();
  64722. };
  64723. /**
  64724. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64725. */
  64726. VideoTexture.prototype.update = function () {
  64727. if (!this.autoUpdateTexture) {
  64728. // Expecting user to call `updateTexture` manually
  64729. return;
  64730. }
  64731. this.updateTexture(true);
  64732. };
  64733. /**
  64734. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64735. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64736. */
  64737. VideoTexture.prototype.updateTexture = function (isVisible) {
  64738. if (!isVisible) {
  64739. return;
  64740. }
  64741. if (this.video.paused && this._stillImageCaptured) {
  64742. return;
  64743. }
  64744. this._stillImageCaptured = true;
  64745. this._updateInternalTexture();
  64746. };
  64747. /**
  64748. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64749. * @param url New url.
  64750. */
  64751. VideoTexture.prototype.updateURL = function (url) {
  64752. this.video.src = url;
  64753. };
  64754. VideoTexture.prototype.dispose = function () {
  64755. _super.prototype.dispose.call(this);
  64756. this.video.removeEventListener("canplay", this._createInternalTexture);
  64757. this.video.removeEventListener("paused", this._updateInternalTexture);
  64758. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64759. this.video.removeEventListener("emptied", this.reset);
  64760. this.video.pause();
  64761. };
  64762. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64763. var video = document.createElement("video");
  64764. var constraintsDeviceId;
  64765. if (constraints && constraints.deviceId) {
  64766. constraintsDeviceId = {
  64767. exact: constraints.deviceId,
  64768. };
  64769. }
  64770. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64771. if (navigator.mediaDevices) {
  64772. navigator.mediaDevices.getUserMedia({ video: constraints })
  64773. .then(function (stream) {
  64774. if (video.mozSrcObject !== undefined) {
  64775. // hack for Firefox < 19
  64776. video.mozSrcObject = stream;
  64777. }
  64778. else {
  64779. video.srcObject = stream;
  64780. }
  64781. var onPlaying = function () {
  64782. if (onReady) {
  64783. onReady(new VideoTexture("video", video, scene, true, true));
  64784. }
  64785. video.removeEventListener("playing", onPlaying);
  64786. };
  64787. video.addEventListener("playing", onPlaying);
  64788. video.play();
  64789. })
  64790. .catch(function (err) {
  64791. BABYLON.Tools.Error(err.name);
  64792. });
  64793. }
  64794. else {
  64795. navigator.getUserMedia =
  64796. navigator.getUserMedia ||
  64797. navigator.webkitGetUserMedia ||
  64798. navigator.mozGetUserMedia ||
  64799. navigator.msGetUserMedia;
  64800. if (navigator.getUserMedia) {
  64801. navigator.getUserMedia({
  64802. video: {
  64803. deviceId: constraintsDeviceId,
  64804. width: {
  64805. min: (constraints && constraints.minWidth) || 256,
  64806. max: (constraints && constraints.maxWidth) || 640,
  64807. },
  64808. height: {
  64809. min: (constraints && constraints.minHeight) || 256,
  64810. max: (constraints && constraints.maxHeight) || 480,
  64811. },
  64812. },
  64813. }, function (stream) {
  64814. if (video.mozSrcObject !== undefined) {
  64815. // hack for Firefox < 19
  64816. video.mozSrcObject = stream;
  64817. }
  64818. else {
  64819. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64820. }
  64821. video.play();
  64822. if (onReady) {
  64823. onReady(new VideoTexture("video", video, scene, true, true));
  64824. }
  64825. }, function (e) {
  64826. BABYLON.Tools.Error(e.name);
  64827. });
  64828. }
  64829. }
  64830. };
  64831. return VideoTexture;
  64832. }(BABYLON.Texture));
  64833. BABYLON.VideoTexture = VideoTexture;
  64834. })(BABYLON || (BABYLON = {}));
  64835. //# sourceMappingURL=babylon.videoTexture.js.map
  64836. var BABYLON;
  64837. (function (BABYLON) {
  64838. var RawTexture = /** @class */ (function (_super) {
  64839. __extends(RawTexture, _super);
  64840. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64841. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64842. if (invertY === void 0) { invertY = false; }
  64843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64844. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64845. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64846. _this.format = format;
  64847. _this._engine = scene.getEngine();
  64848. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64849. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64850. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64851. return _this;
  64852. }
  64853. RawTexture.prototype.update = function (data) {
  64854. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64855. };
  64856. // Statics
  64857. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64859. if (invertY === void 0) { invertY = false; }
  64860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64861. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64862. };
  64863. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64865. if (invertY === void 0) { invertY = false; }
  64866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64867. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64868. };
  64869. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64870. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64871. if (invertY === void 0) { invertY = false; }
  64872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64873. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64874. };
  64875. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64876. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64877. if (invertY === void 0) { invertY = false; }
  64878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64879. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64880. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64881. };
  64882. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64883. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64884. if (invertY === void 0) { invertY = false; }
  64885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64887. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64888. };
  64889. return RawTexture;
  64890. }(BABYLON.Texture));
  64891. BABYLON.RawTexture = RawTexture;
  64892. })(BABYLON || (BABYLON = {}));
  64893. //# sourceMappingURL=babylon.rawTexture.js.map
  64894. var BABYLON;
  64895. (function (BABYLON) {
  64896. /**
  64897. * Class used to store 3D textures containing user data
  64898. */
  64899. var RawTexture3D = /** @class */ (function (_super) {
  64900. __extends(RawTexture3D, _super);
  64901. /**
  64902. * Create a new RawTexture3D
  64903. * @param data defines the data of the texture
  64904. * @param width defines the width of the texture
  64905. * @param height defines the height of the texture
  64906. * @param depth defines the depth of the texture
  64907. * @param format defines the texture format to use
  64908. * @param scene defines the hosting scene
  64909. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64910. * @param invertY defines if texture must be stored with Y axis inverted
  64911. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64912. */
  64913. function RawTexture3D(data, width, height, depth,
  64914. /** Gets or sets the texture format to use*/
  64915. format, scene, generateMipMaps, invertY, samplingMode) {
  64916. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64917. if (invertY === void 0) { invertY = false; }
  64918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64919. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64920. _this.format = format;
  64921. _this._engine = scene.getEngine();
  64922. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64923. _this.is3D = true;
  64924. return _this;
  64925. }
  64926. /**
  64927. * Update the texture with new data
  64928. * @param data defines the data to store in the texture
  64929. */
  64930. RawTexture3D.prototype.update = function (data) {
  64931. if (!this._texture) {
  64932. return;
  64933. }
  64934. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64935. };
  64936. return RawTexture3D;
  64937. }(BABYLON.Texture));
  64938. BABYLON.RawTexture3D = RawTexture3D;
  64939. })(BABYLON || (BABYLON = {}));
  64940. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64941. var BABYLON;
  64942. (function (BABYLON) {
  64943. /**
  64944. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64945. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64946. */
  64947. var PostProcess = /** @class */ (function () {
  64948. /**
  64949. * Creates a new instance PostProcess
  64950. * @param name The name of the PostProcess.
  64951. * @param fragmentUrl The url of the fragment shader to be used.
  64952. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64953. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64954. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64955. * @param camera The camera to apply the render pass to.
  64956. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64957. * @param engine The engine which the post process will be applied. (default: current engine)
  64958. * @param reusable If the post process can be reused on the same frame. (default: false)
  64959. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64960. * @param textureType Type of textures used when performing the post process. (default: 0)
  64961. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64962. * @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
  64963. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64964. */
  64965. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64967. if (defines === void 0) { defines = null; }
  64968. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64969. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64970. if (blockCompilation === void 0) { blockCompilation = false; }
  64971. this.name = name;
  64972. /**
  64973. * Width of the texture to apply the post process on
  64974. */
  64975. this.width = -1;
  64976. /**
  64977. * Height of the texture to apply the post process on
  64978. */
  64979. this.height = -1;
  64980. /**
  64981. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64982. */
  64983. this._outputTexture = null;
  64984. /**
  64985. * If the buffer needs to be cleared before applying the post process. (default: true)
  64986. * Should be set to false if shader will overwrite all previous pixels.
  64987. */
  64988. this.autoClear = true;
  64989. /**
  64990. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64991. */
  64992. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64993. /**
  64994. * Animations to be used for the post processing
  64995. */
  64996. this.animations = new Array();
  64997. /**
  64998. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64999. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65000. */
  65001. this.enablePixelPerfectMode = false;
  65002. /**
  65003. * Force the postprocess to be applied without taking in account viewport
  65004. */
  65005. this.forceFullscreenViewport = true;
  65006. /**
  65007. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65008. */
  65009. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65010. /**
  65011. * Force textures to be a power of two (default: false)
  65012. */
  65013. this.alwaysForcePOT = false;
  65014. /**
  65015. * Number of sample textures (default: 1)
  65016. */
  65017. this.samples = 1;
  65018. /**
  65019. * Modify the scale of the post process to be the same as the viewport (default: false)
  65020. */
  65021. this.adaptScaleToCurrentViewport = false;
  65022. this._reusable = false;
  65023. /**
  65024. * Smart array of input and output textures for the post process.
  65025. */
  65026. this._textures = new BABYLON.SmartArray(2);
  65027. /**
  65028. * The index in _textures that corresponds to the output texture.
  65029. */
  65030. this._currentRenderTextureInd = 0;
  65031. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65032. this._texelSize = BABYLON.Vector2.Zero();
  65033. // Events
  65034. /**
  65035. * An event triggered when the postprocess is activated.
  65036. */
  65037. this.onActivateObservable = new BABYLON.Observable();
  65038. /**
  65039. * An event triggered when the postprocess changes its size.
  65040. */
  65041. this.onSizeChangedObservable = new BABYLON.Observable();
  65042. /**
  65043. * An event triggered when the postprocess applies its effect.
  65044. */
  65045. this.onApplyObservable = new BABYLON.Observable();
  65046. /**
  65047. * An event triggered before rendering the postprocess
  65048. */
  65049. this.onBeforeRenderObservable = new BABYLON.Observable();
  65050. /**
  65051. * An event triggered after rendering the postprocess
  65052. */
  65053. this.onAfterRenderObservable = new BABYLON.Observable();
  65054. if (camera != null) {
  65055. this._camera = camera;
  65056. this._scene = camera.getScene();
  65057. camera.attachPostProcess(this);
  65058. this._engine = this._scene.getEngine();
  65059. this._scene.postProcesses.push(this);
  65060. }
  65061. else if (engine) {
  65062. this._engine = engine;
  65063. this._engine.postProcesses.push(this);
  65064. }
  65065. this._options = options;
  65066. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65067. this._reusable = reusable || false;
  65068. this._textureType = textureType;
  65069. this._samplers = samplers || [];
  65070. this._samplers.push("textureSampler");
  65071. this._fragmentUrl = fragmentUrl;
  65072. this._vertexUrl = vertexUrl;
  65073. this._parameters = parameters || [];
  65074. this._parameters.push("scale");
  65075. this._indexParameters = indexParameters;
  65076. if (!blockCompilation) {
  65077. this.updateEffect(defines);
  65078. }
  65079. }
  65080. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65081. /**
  65082. * A function that is added to the onActivateObservable
  65083. */
  65084. set: function (callback) {
  65085. if (this._onActivateObserver) {
  65086. this.onActivateObservable.remove(this._onActivateObserver);
  65087. }
  65088. if (callback) {
  65089. this._onActivateObserver = this.onActivateObservable.add(callback);
  65090. }
  65091. },
  65092. enumerable: true,
  65093. configurable: true
  65094. });
  65095. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65096. /**
  65097. * A function that is added to the onSizeChangedObservable
  65098. */
  65099. set: function (callback) {
  65100. if (this._onSizeChangedObserver) {
  65101. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65102. }
  65103. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65104. },
  65105. enumerable: true,
  65106. configurable: true
  65107. });
  65108. Object.defineProperty(PostProcess.prototype, "onApply", {
  65109. /**
  65110. * A function that is added to the onApplyObservable
  65111. */
  65112. set: function (callback) {
  65113. if (this._onApplyObserver) {
  65114. this.onApplyObservable.remove(this._onApplyObserver);
  65115. }
  65116. this._onApplyObserver = this.onApplyObservable.add(callback);
  65117. },
  65118. enumerable: true,
  65119. configurable: true
  65120. });
  65121. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65122. /**
  65123. * A function that is added to the onBeforeRenderObservable
  65124. */
  65125. set: function (callback) {
  65126. if (this._onBeforeRenderObserver) {
  65127. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65128. }
  65129. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65130. },
  65131. enumerable: true,
  65132. configurable: true
  65133. });
  65134. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65135. /**
  65136. * A function that is added to the onAfterRenderObservable
  65137. */
  65138. set: function (callback) {
  65139. if (this._onAfterRenderObserver) {
  65140. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65141. }
  65142. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65143. },
  65144. enumerable: true,
  65145. configurable: true
  65146. });
  65147. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65148. /**
  65149. * 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
  65150. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65151. */
  65152. get: function () {
  65153. return this._textures.data[this._currentRenderTextureInd];
  65154. },
  65155. set: function (value) {
  65156. this._forcedOutputTexture = value;
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. /**
  65162. * Gets the camera which post process is applied to.
  65163. * @returns The camera the post process is applied to.
  65164. */
  65165. PostProcess.prototype.getCamera = function () {
  65166. return this._camera;
  65167. };
  65168. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65169. /**
  65170. * Gets the texel size of the postprocess.
  65171. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65172. */
  65173. get: function () {
  65174. if (this._shareOutputWithPostProcess) {
  65175. return this._shareOutputWithPostProcess.texelSize;
  65176. }
  65177. if (this._forcedOutputTexture) {
  65178. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65179. }
  65180. return this._texelSize;
  65181. },
  65182. enumerable: true,
  65183. configurable: true
  65184. });
  65185. /**
  65186. * Gets the engine which this post process belongs to.
  65187. * @returns The engine the post process was enabled with.
  65188. */
  65189. PostProcess.prototype.getEngine = function () {
  65190. return this._engine;
  65191. };
  65192. /**
  65193. * The effect that is created when initializing the post process.
  65194. * @returns The created effect corrisponding the the postprocess.
  65195. */
  65196. PostProcess.prototype.getEffect = function () {
  65197. return this._effect;
  65198. };
  65199. /**
  65200. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65201. * @param postProcess The post process to share the output with.
  65202. * @returns This post process.
  65203. */
  65204. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65205. this._disposeTextures();
  65206. this._shareOutputWithPostProcess = postProcess;
  65207. return this;
  65208. };
  65209. /**
  65210. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65211. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65212. */
  65213. PostProcess.prototype.useOwnOutput = function () {
  65214. if (this._textures.length == 0) {
  65215. this._textures = new BABYLON.SmartArray(2);
  65216. }
  65217. this._shareOutputWithPostProcess = null;
  65218. };
  65219. /**
  65220. * Updates the effect with the current post process compile time values and recompiles the shader.
  65221. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65222. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65223. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65224. * @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
  65225. * @param onCompiled Called when the shader has been compiled.
  65226. * @param onError Called if there is an error when compiling a shader.
  65227. */
  65228. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65229. if (defines === void 0) { defines = null; }
  65230. if (uniforms === void 0) { uniforms = null; }
  65231. if (samplers === void 0) { samplers = null; }
  65232. 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);
  65233. };
  65234. /**
  65235. * The post process is reusable if it can be used multiple times within one frame.
  65236. * @returns If the post process is reusable
  65237. */
  65238. PostProcess.prototype.isReusable = function () {
  65239. return this._reusable;
  65240. };
  65241. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65242. PostProcess.prototype.markTextureDirty = function () {
  65243. this.width = -1;
  65244. };
  65245. /**
  65246. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65247. * 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.
  65248. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65249. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65250. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65251. * @returns The target texture that was bound to be written to.
  65252. */
  65253. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65254. var _this = this;
  65255. if (sourceTexture === void 0) { sourceTexture = null; }
  65256. camera = camera || this._camera;
  65257. var scene = camera.getScene();
  65258. var engine = scene.getEngine();
  65259. var maxSize = engine.getCaps().maxTextureSize;
  65260. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65261. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65262. // 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
  65263. var webVRCamera = camera.parent;
  65264. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65265. requiredWidth /= 2;
  65266. }
  65267. var desiredWidth = (this._options.width || requiredWidth);
  65268. var desiredHeight = this._options.height || requiredHeight;
  65269. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65270. if (this.adaptScaleToCurrentViewport) {
  65271. var currentViewport = engine.currentViewport;
  65272. if (currentViewport) {
  65273. desiredWidth *= currentViewport.width;
  65274. desiredHeight *= currentViewport.height;
  65275. }
  65276. }
  65277. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65278. if (!this._options.width) {
  65279. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65280. }
  65281. if (!this._options.height) {
  65282. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65283. }
  65284. }
  65285. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65286. if (this._textures.length > 0) {
  65287. for (var i = 0; i < this._textures.length; i++) {
  65288. this._engine._releaseTexture(this._textures.data[i]);
  65289. }
  65290. this._textures.reset();
  65291. }
  65292. this.width = desiredWidth;
  65293. this.height = desiredHeight;
  65294. var textureSize = { width: this.width, height: this.height };
  65295. var textureOptions = {
  65296. generateMipMaps: false,
  65297. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65298. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65299. samplingMode: this.renderTargetSamplingMode,
  65300. type: this._textureType
  65301. };
  65302. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65303. if (this._reusable) {
  65304. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65305. }
  65306. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65307. this.onSizeChangedObservable.notifyObservers(this);
  65308. }
  65309. this._textures.forEach(function (texture) {
  65310. if (texture.samples !== _this.samples) {
  65311. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65312. }
  65313. });
  65314. }
  65315. var target;
  65316. if (this._shareOutputWithPostProcess) {
  65317. target = this._shareOutputWithPostProcess.inputTexture;
  65318. }
  65319. else if (this._forcedOutputTexture) {
  65320. target = this._forcedOutputTexture;
  65321. this.width = this._forcedOutputTexture.width;
  65322. this.height = this._forcedOutputTexture.height;
  65323. }
  65324. else {
  65325. target = this.inputTexture;
  65326. }
  65327. // Bind the input of this post process to be used as the output of the previous post process.
  65328. if (this.enablePixelPerfectMode) {
  65329. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65330. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65331. }
  65332. else {
  65333. this._scaleRatio.copyFromFloats(1, 1);
  65334. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65335. }
  65336. this.onActivateObservable.notifyObservers(camera);
  65337. // Clear
  65338. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65339. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65340. }
  65341. if (this._reusable) {
  65342. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65343. }
  65344. return target;
  65345. };
  65346. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65347. /**
  65348. * If the post process is supported.
  65349. */
  65350. get: function () {
  65351. return this._effect.isSupported;
  65352. },
  65353. enumerable: true,
  65354. configurable: true
  65355. });
  65356. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65357. /**
  65358. * The aspect ratio of the output texture.
  65359. */
  65360. get: function () {
  65361. if (this._shareOutputWithPostProcess) {
  65362. return this._shareOutputWithPostProcess.aspectRatio;
  65363. }
  65364. if (this._forcedOutputTexture) {
  65365. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65366. }
  65367. return this.width / this.height;
  65368. },
  65369. enumerable: true,
  65370. configurable: true
  65371. });
  65372. /**
  65373. * Get a value indicating if the post-process is ready to be used
  65374. * @returns true if the post-process is ready (shader is compiled)
  65375. */
  65376. PostProcess.prototype.isReady = function () {
  65377. return this._effect && this._effect.isReady();
  65378. };
  65379. /**
  65380. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65381. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65382. */
  65383. PostProcess.prototype.apply = function () {
  65384. // Check
  65385. if (!this._effect || !this._effect.isReady())
  65386. return null;
  65387. // States
  65388. this._engine.enableEffect(this._effect);
  65389. this._engine.setState(false);
  65390. this._engine.setDepthBuffer(false);
  65391. this._engine.setDepthWrite(false);
  65392. // Alpha
  65393. this._engine.setAlphaMode(this.alphaMode);
  65394. if (this.alphaConstants) {
  65395. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65396. }
  65397. // Bind the output texture of the preivous post process as the input to this post process.
  65398. var source;
  65399. if (this._shareOutputWithPostProcess) {
  65400. source = this._shareOutputWithPostProcess.inputTexture;
  65401. }
  65402. else if (this._forcedOutputTexture) {
  65403. source = this._forcedOutputTexture;
  65404. }
  65405. else {
  65406. source = this.inputTexture;
  65407. }
  65408. this._effect._bindTexture("textureSampler", source);
  65409. // Parameters
  65410. this._effect.setVector2("scale", this._scaleRatio);
  65411. this.onApplyObservable.notifyObservers(this._effect);
  65412. return this._effect;
  65413. };
  65414. PostProcess.prototype._disposeTextures = function () {
  65415. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65416. return;
  65417. }
  65418. if (this._textures.length > 0) {
  65419. for (var i = 0; i < this._textures.length; i++) {
  65420. this._engine._releaseTexture(this._textures.data[i]);
  65421. }
  65422. }
  65423. this._textures.dispose();
  65424. };
  65425. /**
  65426. * Disposes the post process.
  65427. * @param camera The camera to dispose the post process on.
  65428. */
  65429. PostProcess.prototype.dispose = function (camera) {
  65430. camera = camera || this._camera;
  65431. this._disposeTextures();
  65432. if (this._scene) {
  65433. var index_1 = this._scene.postProcesses.indexOf(this);
  65434. if (index_1 !== -1) {
  65435. this._scene.postProcesses.splice(index_1, 1);
  65436. }
  65437. }
  65438. else {
  65439. var index_2 = this._engine.postProcesses.indexOf(this);
  65440. if (index_2 !== -1) {
  65441. this._engine.postProcesses.splice(index_2, 1);
  65442. }
  65443. }
  65444. if (!camera) {
  65445. return;
  65446. }
  65447. camera.detachPostProcess(this);
  65448. var index = camera._postProcesses.indexOf(this);
  65449. if (index === 0 && camera._postProcesses.length > 0) {
  65450. var firstPostProcess = this._camera._getFirstPostProcess();
  65451. if (firstPostProcess) {
  65452. firstPostProcess.markTextureDirty();
  65453. }
  65454. }
  65455. this.onActivateObservable.clear();
  65456. this.onAfterRenderObservable.clear();
  65457. this.onApplyObservable.clear();
  65458. this.onBeforeRenderObservable.clear();
  65459. this.onSizeChangedObservable.clear();
  65460. };
  65461. return PostProcess;
  65462. }());
  65463. BABYLON.PostProcess = PostProcess;
  65464. })(BABYLON || (BABYLON = {}));
  65465. //# sourceMappingURL=babylon.postProcess.js.map
  65466. var BABYLON;
  65467. (function (BABYLON) {
  65468. var PassPostProcess = /** @class */ (function (_super) {
  65469. __extends(PassPostProcess, _super);
  65470. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65471. if (camera === void 0) { camera = null; }
  65472. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65473. if (blockCompilation === void 0) { blockCompilation = false; }
  65474. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65475. }
  65476. return PassPostProcess;
  65477. }(BABYLON.PostProcess));
  65478. BABYLON.PassPostProcess = PassPostProcess;
  65479. })(BABYLON || (BABYLON = {}));
  65480. //# sourceMappingURL=babylon.passPostProcess.js.map
  65481. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65482. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65483. s = arguments[i];
  65484. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65485. t[p] = s[p];
  65486. }
  65487. return t;
  65488. };
  65489. var BABYLON;
  65490. (function (BABYLON) {
  65491. /**
  65492. * Default implementation IShadowGenerator.
  65493. * This is the main object responsible of generating shadows in the framework.
  65494. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65495. */
  65496. var ShadowGenerator = /** @class */ (function () {
  65497. /**
  65498. * Creates a ShadowGenerator object.
  65499. * A ShadowGenerator is the required tool to use the shadows.
  65500. * Each light casting shadows needs to use its own ShadowGenerator.
  65501. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65502. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65503. * @param light The light object generating the shadows.
  65504. * @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.
  65505. */
  65506. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65507. this._bias = 0.00005;
  65508. this._normalBias = 0;
  65509. this._blurBoxOffset = 1;
  65510. this._blurScale = 2;
  65511. this._blurKernel = 1;
  65512. this._useKernelBlur = false;
  65513. this._filter = ShadowGenerator.FILTER_NONE;
  65514. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65515. this._contactHardeningLightSizeUVRatio = 0.1;
  65516. this._darkness = 0;
  65517. this._transparencyShadow = false;
  65518. /**
  65519. * Controls the extent to which the shadows fade out at the edge of the frustum
  65520. * Used only by directionals and spots
  65521. */
  65522. this.frustumEdgeFalloff = 0;
  65523. /**
  65524. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65525. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65526. * It might on the other hand introduce peter panning.
  65527. */
  65528. this.forceBackFacesOnly = false;
  65529. this._lightDirection = BABYLON.Vector3.Zero();
  65530. this._viewMatrix = BABYLON.Matrix.Zero();
  65531. this._projectionMatrix = BABYLON.Matrix.Zero();
  65532. this._transformMatrix = BABYLON.Matrix.Zero();
  65533. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65534. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65535. this._currentFaceIndex = 0;
  65536. this._currentFaceIndexCache = 0;
  65537. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65538. this._mapSize = mapSize;
  65539. this._light = light;
  65540. this._scene = light.getScene();
  65541. light._shadowGenerator = this;
  65542. // Texture type fallback from float to int if not supported.
  65543. var caps = this._scene.getEngine().getCaps();
  65544. if (!useFullFloatFirst) {
  65545. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65546. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65547. }
  65548. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65549. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65550. }
  65551. else {
  65552. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65553. }
  65554. }
  65555. else {
  65556. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65557. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65558. }
  65559. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65560. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65561. }
  65562. else {
  65563. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65564. }
  65565. }
  65566. this._initializeGenerator();
  65567. this._applyFilterValues();
  65568. }
  65569. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65570. /**
  65571. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65572. */
  65573. get: function () {
  65574. return this._bias;
  65575. },
  65576. /**
  65577. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65578. */
  65579. set: function (bias) {
  65580. this._bias = bias;
  65581. },
  65582. enumerable: true,
  65583. configurable: true
  65584. });
  65585. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65586. /**
  65587. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65588. */
  65589. get: function () {
  65590. return this._normalBias;
  65591. },
  65592. /**
  65593. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65594. */
  65595. set: function (normalBias) {
  65596. this._normalBias = normalBias;
  65597. },
  65598. enumerable: true,
  65599. configurable: true
  65600. });
  65601. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65602. /**
  65603. * Gets the blur box offset: offset applied during the blur pass.
  65604. * Only usefull if useKernelBlur = false
  65605. */
  65606. get: function () {
  65607. return this._blurBoxOffset;
  65608. },
  65609. /**
  65610. * Sets the blur box offset: offset applied during the blur pass.
  65611. * Only usefull if useKernelBlur = false
  65612. */
  65613. set: function (value) {
  65614. if (this._blurBoxOffset === value) {
  65615. return;
  65616. }
  65617. this._blurBoxOffset = value;
  65618. this._disposeBlurPostProcesses();
  65619. },
  65620. enumerable: true,
  65621. configurable: true
  65622. });
  65623. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65624. /**
  65625. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65626. * 2 means half of the size.
  65627. */
  65628. get: function () {
  65629. return this._blurScale;
  65630. },
  65631. /**
  65632. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65633. * 2 means half of the size.
  65634. */
  65635. set: function (value) {
  65636. if (this._blurScale === value) {
  65637. return;
  65638. }
  65639. this._blurScale = value;
  65640. this._disposeBlurPostProcesses();
  65641. },
  65642. enumerable: true,
  65643. configurable: true
  65644. });
  65645. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65646. /**
  65647. * Gets the blur kernel: kernel size of the blur pass.
  65648. * Only usefull if useKernelBlur = true
  65649. */
  65650. get: function () {
  65651. return this._blurKernel;
  65652. },
  65653. /**
  65654. * Sets the blur kernel: kernel size of the blur pass.
  65655. * Only usefull if useKernelBlur = true
  65656. */
  65657. set: function (value) {
  65658. if (this._blurKernel === value) {
  65659. return;
  65660. }
  65661. this._blurKernel = value;
  65662. this._disposeBlurPostProcesses();
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65668. /**
  65669. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65670. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65671. */
  65672. get: function () {
  65673. return this._useKernelBlur;
  65674. },
  65675. /**
  65676. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65677. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65678. */
  65679. set: function (value) {
  65680. if (this._useKernelBlur === value) {
  65681. return;
  65682. }
  65683. this._useKernelBlur = value;
  65684. this._disposeBlurPostProcesses();
  65685. },
  65686. enumerable: true,
  65687. configurable: true
  65688. });
  65689. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65690. /**
  65691. * Gets the depth scale used in ESM mode.
  65692. */
  65693. get: function () {
  65694. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65695. },
  65696. /**
  65697. * Sets the depth scale used in ESM mode.
  65698. * This can override the scale stored on the light.
  65699. */
  65700. set: function (value) {
  65701. this._depthScale = value;
  65702. },
  65703. enumerable: true,
  65704. configurable: true
  65705. });
  65706. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65707. /**
  65708. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65709. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65710. */
  65711. get: function () {
  65712. return this._filter;
  65713. },
  65714. /**
  65715. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65716. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65717. */
  65718. set: function (value) {
  65719. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65720. if (this._light.needCube()) {
  65721. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65722. this.useExponentialShadowMap = true;
  65723. return;
  65724. }
  65725. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65726. this.useCloseExponentialShadowMap = true;
  65727. return;
  65728. }
  65729. // PCF on cubemap would also be expensive
  65730. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65731. this.usePoissonSampling = true;
  65732. return;
  65733. }
  65734. }
  65735. // Weblg1 fallback for PCF.
  65736. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65737. if (this._scene.getEngine().webGLVersion === 1) {
  65738. this.usePoissonSampling = true;
  65739. return;
  65740. }
  65741. }
  65742. if (this._filter === value) {
  65743. return;
  65744. }
  65745. this._filter = value;
  65746. this._disposeBlurPostProcesses();
  65747. this._applyFilterValues();
  65748. this._light._markMeshesAsLightDirty();
  65749. },
  65750. enumerable: true,
  65751. configurable: true
  65752. });
  65753. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65754. /**
  65755. * Gets if the current filter is set to Poisson Sampling.
  65756. */
  65757. get: function () {
  65758. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65759. },
  65760. /**
  65761. * Sets the current filter to Poisson Sampling.
  65762. */
  65763. set: function (value) {
  65764. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65765. return;
  65766. }
  65767. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65768. },
  65769. enumerable: true,
  65770. configurable: true
  65771. });
  65772. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65773. /**
  65774. * Gets if the current filter is set to VSM.
  65775. * DEPRECATED. Should use useExponentialShadowMap instead.
  65776. */
  65777. get: function () {
  65778. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65779. return this.useExponentialShadowMap;
  65780. },
  65781. /**
  65782. * Sets the current filter is to VSM.
  65783. * DEPRECATED. Should use useExponentialShadowMap instead.
  65784. */
  65785. set: function (value) {
  65786. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65787. this.useExponentialShadowMap = value;
  65788. },
  65789. enumerable: true,
  65790. configurable: true
  65791. });
  65792. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65793. /**
  65794. * Gets if the current filter is set to blurred VSM.
  65795. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65796. */
  65797. get: function () {
  65798. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65799. return this.useBlurExponentialShadowMap;
  65800. },
  65801. /**
  65802. * Sets the current filter is to blurred VSM.
  65803. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65804. */
  65805. set: function (value) {
  65806. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65807. this.useBlurExponentialShadowMap = value;
  65808. },
  65809. enumerable: true,
  65810. configurable: true
  65811. });
  65812. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65813. /**
  65814. * Gets if the current filter is set to ESM.
  65815. */
  65816. get: function () {
  65817. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65818. },
  65819. /**
  65820. * Sets the current filter is to ESM.
  65821. */
  65822. set: function (value) {
  65823. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65824. return;
  65825. }
  65826. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65827. },
  65828. enumerable: true,
  65829. configurable: true
  65830. });
  65831. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65832. /**
  65833. * Gets if the current filter is set to filtered ESM.
  65834. */
  65835. get: function () {
  65836. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65837. },
  65838. /**
  65839. * Gets if the current filter is set to filtered ESM.
  65840. */
  65841. set: function (value) {
  65842. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65843. return;
  65844. }
  65845. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65846. },
  65847. enumerable: true,
  65848. configurable: true
  65849. });
  65850. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65851. /**
  65852. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65853. * exponential to prevent steep falloff artifacts).
  65854. */
  65855. get: function () {
  65856. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65857. },
  65858. /**
  65859. * Sets the current filter to "close ESM" (using the inverse of the
  65860. * exponential to prevent steep falloff artifacts).
  65861. */
  65862. set: function (value) {
  65863. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65864. return;
  65865. }
  65866. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65867. },
  65868. enumerable: true,
  65869. configurable: true
  65870. });
  65871. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65872. /**
  65873. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65874. * exponential to prevent steep falloff artifacts).
  65875. */
  65876. get: function () {
  65877. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65878. },
  65879. /**
  65880. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65881. * exponential to prevent steep falloff artifacts).
  65882. */
  65883. set: function (value) {
  65884. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65885. return;
  65886. }
  65887. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65888. },
  65889. enumerable: true,
  65890. configurable: true
  65891. });
  65892. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65893. /**
  65894. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65895. */
  65896. get: function () {
  65897. return this.filter === ShadowGenerator.FILTER_PCF;
  65898. },
  65899. /**
  65900. * Sets the current filter to "PCF" (percentage closer filtering).
  65901. */
  65902. set: function (value) {
  65903. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65904. return;
  65905. }
  65906. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65912. /**
  65913. * Gets the PCF or PCSS Quality.
  65914. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65915. */
  65916. get: function () {
  65917. return this._filteringQuality;
  65918. },
  65919. /**
  65920. * Sets the PCF or PCSS Quality.
  65921. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65922. */
  65923. set: function (filteringQuality) {
  65924. this._filteringQuality = filteringQuality;
  65925. },
  65926. enumerable: true,
  65927. configurable: true
  65928. });
  65929. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65930. /**
  65931. * Gets if the current filter is set to "PCSS" (contact hardening).
  65932. */
  65933. get: function () {
  65934. return this.filter === ShadowGenerator.FILTER_PCSS;
  65935. },
  65936. /**
  65937. * Sets the current filter to "PCSS" (contact hardening).
  65938. */
  65939. set: function (value) {
  65940. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65941. return;
  65942. }
  65943. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65944. },
  65945. enumerable: true,
  65946. configurable: true
  65947. });
  65948. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65949. /**
  65950. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65951. * Using a ratio helps keeping shape stability independently of the map size.
  65952. *
  65953. * It does not account for the light projection as it was having too much
  65954. * instability during the light setup or during light position changes.
  65955. *
  65956. * Only valid if useContactHardeningShadow is true.
  65957. */
  65958. get: function () {
  65959. return this._contactHardeningLightSizeUVRatio;
  65960. },
  65961. /**
  65962. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65963. * Using a ratio helps keeping shape stability independently of the map size.
  65964. *
  65965. * It does not account for the light projection as it was having too much
  65966. * instability during the light setup or during light position changes.
  65967. *
  65968. * Only valid if useContactHardeningShadow is true.
  65969. */
  65970. set: function (contactHardeningLightSizeUVRatio) {
  65971. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65972. },
  65973. enumerable: true,
  65974. configurable: true
  65975. });
  65976. /**
  65977. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65978. * 0 means strongest and 1 would means no shadow.
  65979. * @returns the darkness.
  65980. */
  65981. ShadowGenerator.prototype.getDarkness = function () {
  65982. return this._darkness;
  65983. };
  65984. /**
  65985. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65986. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65987. * @returns the shadow generator allowing fluent coding.
  65988. */
  65989. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65990. if (darkness >= 1.0)
  65991. this._darkness = 1.0;
  65992. else if (darkness <= 0.0)
  65993. this._darkness = 0.0;
  65994. else
  65995. this._darkness = darkness;
  65996. return this;
  65997. };
  65998. /**
  65999. * Sets the ability to have transparent shadow (boolean).
  66000. * @param transparent True if transparent else False
  66001. * @returns the shadow generator allowing fluent coding
  66002. */
  66003. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66004. this._transparencyShadow = transparent;
  66005. return this;
  66006. };
  66007. /**
  66008. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66009. * @returns The render target texture if present otherwise, null
  66010. */
  66011. ShadowGenerator.prototype.getShadowMap = function () {
  66012. return this._shadowMap;
  66013. };
  66014. /**
  66015. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66016. * @returns The render target texture if the shadow map is present otherwise, null
  66017. */
  66018. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66019. if (this._shadowMap2) {
  66020. return this._shadowMap2;
  66021. }
  66022. return this._shadowMap;
  66023. };
  66024. /**
  66025. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66026. * @param mesh Mesh to add
  66027. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66028. * @returns the Shadow Generator itself
  66029. */
  66030. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66031. if (includeDescendants === void 0) { includeDescendants = true; }
  66032. if (!this._shadowMap) {
  66033. return this;
  66034. }
  66035. if (!this._shadowMap.renderList) {
  66036. this._shadowMap.renderList = [];
  66037. }
  66038. this._shadowMap.renderList.push(mesh);
  66039. if (includeDescendants) {
  66040. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66041. }
  66042. return this;
  66043. var _a;
  66044. };
  66045. /**
  66046. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66047. * @param mesh Mesh to remove
  66048. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66049. * @returns the Shadow Generator itself
  66050. */
  66051. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66052. if (includeDescendants === void 0) { includeDescendants = true; }
  66053. if (!this._shadowMap || !this._shadowMap.renderList) {
  66054. return this;
  66055. }
  66056. var index = this._shadowMap.renderList.indexOf(mesh);
  66057. if (index !== -1) {
  66058. this._shadowMap.renderList.splice(index, 1);
  66059. }
  66060. if (includeDescendants) {
  66061. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66062. var child = _a[_i];
  66063. this.removeShadowCaster(child);
  66064. }
  66065. }
  66066. return this;
  66067. };
  66068. /**
  66069. * Returns the associated light object.
  66070. * @returns the light generating the shadow
  66071. */
  66072. ShadowGenerator.prototype.getLight = function () {
  66073. return this._light;
  66074. };
  66075. ShadowGenerator.prototype._initializeGenerator = function () {
  66076. this._light._markMeshesAsLightDirty();
  66077. this._initializeShadowMap();
  66078. };
  66079. ShadowGenerator.prototype._initializeShadowMap = function () {
  66080. var _this = this;
  66081. // Render target
  66082. var engine = this._scene.getEngine();
  66083. if (engine.webGLVersion > 1) {
  66084. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66085. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66086. }
  66087. else {
  66088. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66089. }
  66090. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66091. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66092. this._shadowMap.anisotropicFilteringLevel = 1;
  66093. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66094. this._shadowMap.renderParticles = false;
  66095. this._shadowMap.ignoreCameraViewport = true;
  66096. // Record Face Index before render.
  66097. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66098. _this._currentFaceIndex = faceIndex;
  66099. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66100. engine.setColorWrite(false);
  66101. }
  66102. });
  66103. // Custom render function.
  66104. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66105. // Blur if required afer render.
  66106. this._shadowMap.onAfterUnbindObservable.add(function () {
  66107. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66108. engine.setColorWrite(true);
  66109. }
  66110. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66111. return;
  66112. }
  66113. var shadowMap = _this.getShadowMapForRendering();
  66114. if (shadowMap) {
  66115. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66116. }
  66117. });
  66118. // Clear according to the chosen filter.
  66119. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66120. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66121. this._shadowMap.onClearObservable.add(function (engine) {
  66122. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66123. engine.clear(clearOne, false, true, false);
  66124. }
  66125. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66126. engine.clear(clearZero, true, true, false);
  66127. }
  66128. else {
  66129. engine.clear(clearOne, true, true, false);
  66130. }
  66131. });
  66132. };
  66133. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66134. var _this = this;
  66135. var engine = this._scene.getEngine();
  66136. var targetSize = this._mapSize / this.blurScale;
  66137. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66138. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66139. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66140. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66141. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66142. }
  66143. if (this.useKernelBlur) {
  66144. 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);
  66145. this._kernelBlurXPostprocess.width = targetSize;
  66146. this._kernelBlurXPostprocess.height = targetSize;
  66147. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66148. effect.setTexture("textureSampler", _this._shadowMap);
  66149. });
  66150. 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);
  66151. this._kernelBlurXPostprocess.autoClear = false;
  66152. this._kernelBlurYPostprocess.autoClear = false;
  66153. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66154. this._kernelBlurXPostprocess.packedFloat = true;
  66155. this._kernelBlurYPostprocess.packedFloat = true;
  66156. }
  66157. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66158. }
  66159. else {
  66160. 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);
  66161. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66162. effect.setFloat2("screenSize", targetSize, targetSize);
  66163. effect.setTexture("textureSampler", _this._shadowMap);
  66164. });
  66165. this._boxBlurPostprocess.autoClear = false;
  66166. this._blurPostProcesses = [this._boxBlurPostprocess];
  66167. }
  66168. };
  66169. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66170. var index;
  66171. var engine = this._scene.getEngine();
  66172. if (depthOnlySubMeshes.length) {
  66173. engine.setColorWrite(false);
  66174. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66175. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66176. }
  66177. engine.setColorWrite(true);
  66178. }
  66179. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66180. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66181. }
  66182. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66183. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66184. }
  66185. if (this._transparencyShadow) {
  66186. for (index = 0; index < transparentSubMeshes.length; index++) {
  66187. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66188. }
  66189. }
  66190. };
  66191. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66192. var _this = this;
  66193. var mesh = subMesh.getRenderingMesh();
  66194. var scene = this._scene;
  66195. var engine = scene.getEngine();
  66196. var material = subMesh.getMaterial();
  66197. if (!material) {
  66198. return;
  66199. }
  66200. // Culling
  66201. engine.setState(material.backFaceCulling);
  66202. // Managing instances
  66203. var batch = mesh._getInstancesRenderList(subMesh._id);
  66204. if (batch.mustReturn) {
  66205. return;
  66206. }
  66207. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66208. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66209. engine.enableEffect(this._effect);
  66210. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66211. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66212. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66213. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66214. this._effect.setVector3("lightData", this._cachedDirection);
  66215. }
  66216. else {
  66217. this._effect.setVector3("lightData", this._cachedPosition);
  66218. }
  66219. if (scene.activeCamera) {
  66220. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66221. }
  66222. // Alpha test
  66223. if (material && material.needAlphaTesting()) {
  66224. var alphaTexture = material.getAlphaTestTexture();
  66225. if (alphaTexture) {
  66226. this._effect.setTexture("diffuseSampler", alphaTexture);
  66227. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66228. }
  66229. }
  66230. // Bones
  66231. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66232. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66233. }
  66234. // Morph targets
  66235. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66236. if (this.forceBackFacesOnly) {
  66237. engine.setState(true, 0, false, true);
  66238. }
  66239. // Draw
  66240. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66241. if (this.forceBackFacesOnly) {
  66242. engine.setState(true, 0, false, false);
  66243. }
  66244. }
  66245. else {
  66246. // Need to reset refresh rate of the shadowMap
  66247. if (this._shadowMap) {
  66248. this._shadowMap.resetRefreshCounter();
  66249. }
  66250. }
  66251. };
  66252. ShadowGenerator.prototype._applyFilterValues = function () {
  66253. if (!this._shadowMap) {
  66254. return;
  66255. }
  66256. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66257. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66258. }
  66259. else {
  66260. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66261. }
  66262. };
  66263. /**
  66264. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66265. * @param onCompiled Callback triggered at the and of the effects compilation
  66266. * @param options Sets of optional options forcing the compilation with different modes
  66267. */
  66268. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66269. var _this = this;
  66270. var localOptions = __assign({ useInstances: false }, options);
  66271. var shadowMap = this.getShadowMap();
  66272. if (!shadowMap) {
  66273. if (onCompiled) {
  66274. onCompiled(this);
  66275. }
  66276. return;
  66277. }
  66278. var renderList = shadowMap.renderList;
  66279. if (!renderList) {
  66280. if (onCompiled) {
  66281. onCompiled(this);
  66282. }
  66283. return;
  66284. }
  66285. var subMeshes = new Array();
  66286. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66287. var mesh = renderList_1[_i];
  66288. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66289. }
  66290. if (subMeshes.length === 0) {
  66291. if (onCompiled) {
  66292. onCompiled(this);
  66293. }
  66294. return;
  66295. }
  66296. var currentIndex = 0;
  66297. var checkReady = function () {
  66298. if (!_this._scene || !_this._scene.getEngine()) {
  66299. return;
  66300. }
  66301. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66302. currentIndex++;
  66303. if (currentIndex >= subMeshes.length) {
  66304. if (onCompiled) {
  66305. onCompiled(_this);
  66306. }
  66307. return;
  66308. }
  66309. }
  66310. setTimeout(checkReady, 16);
  66311. };
  66312. checkReady();
  66313. };
  66314. /**
  66315. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66316. * @param options Sets of optional options forcing the compilation with different modes
  66317. * @returns A promise that resolves when the compilation completes
  66318. */
  66319. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66320. var _this = this;
  66321. return new Promise(function (resolve) {
  66322. _this.forceCompilation(function () {
  66323. resolve();
  66324. }, options);
  66325. });
  66326. };
  66327. /**
  66328. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66329. * @param subMesh The submesh we want to render in the shadow map
  66330. * @param useInstances Defines wether will draw in the map using instances
  66331. * @returns true if ready otherwise, false
  66332. */
  66333. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66334. var defines = [];
  66335. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66336. defines.push("#define FLOAT");
  66337. }
  66338. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66339. defines.push("#define ESM");
  66340. }
  66341. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66342. defines.push("#define DEPTHTEXTURE");
  66343. }
  66344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66345. var mesh = subMesh.getMesh();
  66346. var material = subMesh.getMaterial();
  66347. // Normal bias.
  66348. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66349. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66350. defines.push("#define NORMAL");
  66351. if (mesh.nonUniformScaling) {
  66352. defines.push("#define NONUNIFORMSCALING");
  66353. }
  66354. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66355. defines.push("#define DIRECTIONINLIGHTDATA");
  66356. }
  66357. }
  66358. // Alpha test
  66359. if (material && material.needAlphaTesting()) {
  66360. var alphaTexture = material.getAlphaTestTexture();
  66361. if (alphaTexture) {
  66362. defines.push("#define ALPHATEST");
  66363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66364. attribs.push(BABYLON.VertexBuffer.UVKind);
  66365. defines.push("#define UV1");
  66366. }
  66367. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66368. if (alphaTexture.coordinatesIndex === 1) {
  66369. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66370. defines.push("#define UV2");
  66371. }
  66372. }
  66373. }
  66374. }
  66375. // Bones
  66376. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66379. if (mesh.numBoneInfluencers > 4) {
  66380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66382. }
  66383. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66384. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66385. }
  66386. else {
  66387. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66388. }
  66389. // Morph targets
  66390. var manager = mesh.morphTargetManager;
  66391. var morphInfluencers = 0;
  66392. if (manager) {
  66393. if (manager.numInfluencers > 0) {
  66394. defines.push("#define MORPHTARGETS");
  66395. morphInfluencers = manager.numInfluencers;
  66396. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66397. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66398. }
  66399. }
  66400. // Instances
  66401. if (useInstances) {
  66402. defines.push("#define INSTANCES");
  66403. attribs.push("world0");
  66404. attribs.push("world1");
  66405. attribs.push("world2");
  66406. attribs.push("world3");
  66407. }
  66408. // Get correct effect
  66409. var join = defines.join("\n");
  66410. if (this._cachedDefines !== join) {
  66411. this._cachedDefines = join;
  66412. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66413. }
  66414. if (!this._effect.isReady()) {
  66415. return false;
  66416. }
  66417. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66418. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66419. this._initializeBlurRTTAndPostProcesses();
  66420. }
  66421. }
  66422. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66423. return false;
  66424. }
  66425. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66426. return false;
  66427. }
  66428. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66429. return false;
  66430. }
  66431. return true;
  66432. };
  66433. /**
  66434. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66435. * @param defines Defines of the material we want to update
  66436. * @param lightIndex Index of the light in the enabled light list of the material
  66437. */
  66438. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66439. var scene = this._scene;
  66440. var light = this._light;
  66441. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66442. return;
  66443. }
  66444. defines["SHADOW" + lightIndex] = true;
  66445. if (this.useContactHardeningShadow) {
  66446. defines["SHADOWPCSS" + lightIndex] = true;
  66447. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66448. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66449. }
  66450. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66451. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66452. }
  66453. // else default to high.
  66454. }
  66455. if (this.usePercentageCloserFiltering) {
  66456. defines["SHADOWPCF" + lightIndex] = true;
  66457. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66458. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66459. }
  66460. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66461. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66462. }
  66463. // else default to high.
  66464. }
  66465. else if (this.usePoissonSampling) {
  66466. defines["SHADOWPOISSON" + lightIndex] = true;
  66467. }
  66468. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66469. defines["SHADOWESM" + lightIndex] = true;
  66470. }
  66471. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66472. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66473. }
  66474. if (light.needCube()) {
  66475. defines["SHADOWCUBE" + lightIndex] = true;
  66476. }
  66477. };
  66478. /**
  66479. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66480. * defined in the generator but impacting the effect).
  66481. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66482. * @param effect The effect we are binfing the information for
  66483. */
  66484. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66485. var light = this._light;
  66486. var scene = this._scene;
  66487. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66488. return;
  66489. }
  66490. var camera = scene.activeCamera;
  66491. if (!camera) {
  66492. return;
  66493. }
  66494. var shadowMap = this.getShadowMap();
  66495. if (!shadowMap) {
  66496. return;
  66497. }
  66498. if (!light.needCube()) {
  66499. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66500. }
  66501. // Only PCF uses depth stencil texture.
  66502. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66503. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66504. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66505. }
  66506. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66507. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66508. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66509. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66510. }
  66511. else {
  66512. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66513. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66514. }
  66515. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66516. };
  66517. /**
  66518. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66519. * (eq to shadow prjection matrix * light transform matrix)
  66520. * @returns The transform matrix used to create the shadow map
  66521. */
  66522. ShadowGenerator.prototype.getTransformMatrix = function () {
  66523. var scene = this._scene;
  66524. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66525. return this._transformMatrix;
  66526. }
  66527. this._currentRenderID = scene.getRenderId();
  66528. this._currentFaceIndexCache = this._currentFaceIndex;
  66529. var lightPosition = this._light.position;
  66530. if (this._light.computeTransformedInformation()) {
  66531. lightPosition = this._light.transformedPosition;
  66532. }
  66533. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66534. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66535. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66536. }
  66537. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66538. this._cachedPosition.copyFrom(lightPosition);
  66539. this._cachedDirection.copyFrom(this._lightDirection);
  66540. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66541. var shadowMap = this.getShadowMap();
  66542. if (shadowMap) {
  66543. var renderList = shadowMap.renderList;
  66544. if (renderList) {
  66545. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66546. }
  66547. }
  66548. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66549. }
  66550. return this._transformMatrix;
  66551. };
  66552. /**
  66553. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66554. * Cube and 2D textures for instance.
  66555. */
  66556. ShadowGenerator.prototype.recreateShadowMap = function () {
  66557. var shadowMap = this._shadowMap;
  66558. if (!shadowMap) {
  66559. return;
  66560. }
  66561. // Track render list.
  66562. var renderList = shadowMap.renderList;
  66563. // Clean up existing data.
  66564. this._disposeRTTandPostProcesses();
  66565. // Reinitializes.
  66566. this._initializeGenerator();
  66567. // Reaffect the filter to ensure a correct fallback if necessary.
  66568. this.filter = this.filter;
  66569. // Reaffect the filter.
  66570. this._applyFilterValues();
  66571. // Reaffect Render List.
  66572. this._shadowMap.renderList = renderList;
  66573. };
  66574. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66575. if (this._shadowMap2) {
  66576. this._shadowMap2.dispose();
  66577. this._shadowMap2 = null;
  66578. }
  66579. if (this._boxBlurPostprocess) {
  66580. this._boxBlurPostprocess.dispose();
  66581. this._boxBlurPostprocess = null;
  66582. }
  66583. if (this._kernelBlurXPostprocess) {
  66584. this._kernelBlurXPostprocess.dispose();
  66585. this._kernelBlurXPostprocess = null;
  66586. }
  66587. if (this._kernelBlurYPostprocess) {
  66588. this._kernelBlurYPostprocess.dispose();
  66589. this._kernelBlurYPostprocess = null;
  66590. }
  66591. this._blurPostProcesses = [];
  66592. };
  66593. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66594. if (this._shadowMap) {
  66595. this._shadowMap.dispose();
  66596. this._shadowMap = null;
  66597. }
  66598. this._disposeBlurPostProcesses();
  66599. };
  66600. /**
  66601. * Disposes the ShadowGenerator.
  66602. * Returns nothing.
  66603. */
  66604. ShadowGenerator.prototype.dispose = function () {
  66605. this._disposeRTTandPostProcesses();
  66606. if (this._light) {
  66607. this._light._shadowGenerator = null;
  66608. this._light._markMeshesAsLightDirty();
  66609. }
  66610. };
  66611. /**
  66612. * Serializes the shadow generator setup to a json object.
  66613. * @returns The serialized JSON object
  66614. */
  66615. ShadowGenerator.prototype.serialize = function () {
  66616. var serializationObject = {};
  66617. var shadowMap = this.getShadowMap();
  66618. if (!shadowMap) {
  66619. return serializationObject;
  66620. }
  66621. serializationObject.lightId = this._light.id;
  66622. serializationObject.mapSize = shadowMap.getRenderSize();
  66623. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66624. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66625. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66626. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66627. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66628. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66629. serializationObject.depthScale = this.depthScale;
  66630. serializationObject.darkness = this.getDarkness();
  66631. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66632. serializationObject.blurKernel = this.blurKernel;
  66633. serializationObject.blurScale = this.blurScale;
  66634. serializationObject.useKernelBlur = this.useKernelBlur;
  66635. serializationObject.transparencyShadow = this._transparencyShadow;
  66636. serializationObject.bias = this.bias;
  66637. serializationObject.normalBias = this.normalBias;
  66638. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66639. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66640. serializationObject.filteringQuality = this.filteringQuality;
  66641. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66642. serializationObject.renderList = [];
  66643. if (shadowMap.renderList) {
  66644. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66645. var mesh = shadowMap.renderList[meshIndex];
  66646. serializationObject.renderList.push(mesh.id);
  66647. }
  66648. }
  66649. return serializationObject;
  66650. };
  66651. /**
  66652. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66653. * @param parsedShadowGenerator The JSON object to parse
  66654. * @param scene The scene to create the shadow map for
  66655. * @returns The parsed shadow generator
  66656. */
  66657. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66658. //casting to point light, as light is missing the position attr and typescript complains.
  66659. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66660. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66661. var shadowMap = shadowGenerator.getShadowMap();
  66662. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66663. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66664. meshes.forEach(function (mesh) {
  66665. if (!shadowMap) {
  66666. return;
  66667. }
  66668. if (!shadowMap.renderList) {
  66669. shadowMap.renderList = [];
  66670. }
  66671. shadowMap.renderList.push(mesh);
  66672. });
  66673. }
  66674. if (parsedShadowGenerator.usePoissonSampling) {
  66675. shadowGenerator.usePoissonSampling = true;
  66676. }
  66677. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66678. shadowGenerator.useExponentialShadowMap = true;
  66679. }
  66680. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66681. shadowGenerator.useBlurExponentialShadowMap = true;
  66682. }
  66683. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66684. shadowGenerator.useCloseExponentialShadowMap = true;
  66685. }
  66686. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66687. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66688. }
  66689. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66690. shadowGenerator.usePercentageCloserFiltering = true;
  66691. }
  66692. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66693. shadowGenerator.useContactHardeningShadow = true;
  66694. }
  66695. if (parsedShadowGenerator.filteringQuality) {
  66696. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66697. }
  66698. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66699. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66700. }
  66701. // Backward compat
  66702. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66703. shadowGenerator.useExponentialShadowMap = true;
  66704. }
  66705. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66706. shadowGenerator.useBlurExponentialShadowMap = true;
  66707. }
  66708. if (parsedShadowGenerator.depthScale) {
  66709. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66710. }
  66711. if (parsedShadowGenerator.blurScale) {
  66712. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66713. }
  66714. if (parsedShadowGenerator.blurBoxOffset) {
  66715. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66716. }
  66717. if (parsedShadowGenerator.useKernelBlur) {
  66718. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66719. }
  66720. if (parsedShadowGenerator.blurKernel) {
  66721. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66722. }
  66723. if (parsedShadowGenerator.bias !== undefined) {
  66724. shadowGenerator.bias = parsedShadowGenerator.bias;
  66725. }
  66726. if (parsedShadowGenerator.normalBias !== undefined) {
  66727. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66728. }
  66729. if (parsedShadowGenerator.darkness) {
  66730. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66731. }
  66732. if (parsedShadowGenerator.transparencyShadow) {
  66733. shadowGenerator.setTransparencyShadow(true);
  66734. }
  66735. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66736. return shadowGenerator;
  66737. };
  66738. /**
  66739. * Shadow generator mode None: no filtering applied.
  66740. */
  66741. ShadowGenerator.FILTER_NONE = 0;
  66742. /**
  66743. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66744. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66745. */
  66746. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66747. /**
  66748. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66749. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66750. */
  66751. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66752. /**
  66753. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66754. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66755. */
  66756. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66757. /**
  66758. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66759. * edge artifacts on steep falloff.
  66760. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66761. */
  66762. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66763. /**
  66764. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66765. * edge artifacts on steep falloff.
  66766. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66767. */
  66768. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66769. /**
  66770. * Shadow generator mode PCF: Percentage Closer Filtering
  66771. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66772. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66773. */
  66774. ShadowGenerator.FILTER_PCF = 6;
  66775. /**
  66776. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66777. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66778. * Contact Hardening
  66779. */
  66780. ShadowGenerator.FILTER_PCSS = 7;
  66781. /**
  66782. * Reserved for PCF and PCSS
  66783. * Highest Quality.
  66784. *
  66785. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66786. *
  66787. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66788. */
  66789. ShadowGenerator.QUALITY_HIGH = 0;
  66790. /**
  66791. * Reserved for PCF and PCSS
  66792. * Good tradeoff for quality/perf cross devices
  66793. *
  66794. * Execute PCF on a 3*3 kernel.
  66795. *
  66796. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66797. */
  66798. ShadowGenerator.QUALITY_MEDIUM = 1;
  66799. /**
  66800. * Reserved for PCF and PCSS
  66801. * The lowest quality but the fastest.
  66802. *
  66803. * Execute PCF on a 1*1 kernel.
  66804. *
  66805. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66806. */
  66807. ShadowGenerator.QUALITY_LOW = 2;
  66808. return ShadowGenerator;
  66809. }());
  66810. BABYLON.ShadowGenerator = ShadowGenerator;
  66811. })(BABYLON || (BABYLON = {}));
  66812. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66813. var BABYLON;
  66814. (function (BABYLON) {
  66815. var DefaultLoadingScreen = /** @class */ (function () {
  66816. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66817. if (_loadingText === void 0) { _loadingText = ""; }
  66818. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66819. var _this = this;
  66820. this._renderingCanvas = _renderingCanvas;
  66821. this._loadingText = _loadingText;
  66822. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66823. // Resize
  66824. this._resizeLoadingUI = function () {
  66825. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66826. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66827. if (!_this._loadingDiv) {
  66828. return;
  66829. }
  66830. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66831. _this._loadingDiv.style.left = canvasRect.left + "px";
  66832. _this._loadingDiv.style.top = canvasRect.top + "px";
  66833. _this._loadingDiv.style.width = canvasRect.width + "px";
  66834. _this._loadingDiv.style.height = canvasRect.height + "px";
  66835. };
  66836. }
  66837. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66838. if (this._loadingDiv) {
  66839. // Do not add a loading screen if there is already one
  66840. return;
  66841. }
  66842. this._loadingDiv = document.createElement("div");
  66843. this._loadingDiv.id = "babylonjsLoadingDiv";
  66844. this._loadingDiv.style.opacity = "0";
  66845. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66846. this._loadingDiv.style.pointerEvents = "none";
  66847. // Loading text
  66848. this._loadingTextDiv = document.createElement("div");
  66849. this._loadingTextDiv.style.position = "absolute";
  66850. this._loadingTextDiv.style.left = "0";
  66851. this._loadingTextDiv.style.top = "50%";
  66852. this._loadingTextDiv.style.marginTop = "80px";
  66853. this._loadingTextDiv.style.width = "100%";
  66854. this._loadingTextDiv.style.height = "20px";
  66855. this._loadingTextDiv.style.fontFamily = "Arial";
  66856. this._loadingTextDiv.style.fontSize = "14px";
  66857. this._loadingTextDiv.style.color = "white";
  66858. this._loadingTextDiv.style.textAlign = "center";
  66859. this._loadingTextDiv.innerHTML = "Loading";
  66860. this._loadingDiv.appendChild(this._loadingTextDiv);
  66861. //set the predefined text
  66862. this._loadingTextDiv.innerHTML = this._loadingText;
  66863. // Generating keyframes
  66864. var style = document.createElement('style');
  66865. style.type = 'text/css';
  66866. 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 }";
  66867. style.innerHTML = keyFrames;
  66868. document.getElementsByTagName('head')[0].appendChild(style);
  66869. // Loading img
  66870. var imgBack = new Image();
  66871. 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";
  66872. imgBack.style.position = "absolute";
  66873. imgBack.style.left = "50%";
  66874. imgBack.style.top = "50%";
  66875. imgBack.style.marginLeft = "-60px";
  66876. imgBack.style.marginTop = "-60px";
  66877. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66878. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66879. imgBack.style.transformOrigin = "50% 50%";
  66880. imgBack.style.webkitTransformOrigin = "50% 50%";
  66881. this._loadingDiv.appendChild(imgBack);
  66882. this._resizeLoadingUI();
  66883. window.addEventListener("resize", this._resizeLoadingUI);
  66884. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66885. document.body.appendChild(this._loadingDiv);
  66886. this._loadingDiv.style.opacity = "1";
  66887. };
  66888. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66889. var _this = this;
  66890. if (!this._loadingDiv) {
  66891. return;
  66892. }
  66893. var onTransitionEnd = function () {
  66894. if (!_this._loadingDiv) {
  66895. return;
  66896. }
  66897. document.body.removeChild(_this._loadingDiv);
  66898. window.removeEventListener("resize", _this._resizeLoadingUI);
  66899. _this._loadingDiv = null;
  66900. };
  66901. this._loadingDiv.style.opacity = "0";
  66902. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66903. };
  66904. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66905. set: function (text) {
  66906. this._loadingText = text;
  66907. if (this._loadingTextDiv) {
  66908. this._loadingTextDiv.innerHTML = this._loadingText;
  66909. }
  66910. },
  66911. enumerable: true,
  66912. configurable: true
  66913. });
  66914. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66915. get: function () {
  66916. return this._loadingDivBackgroundColor;
  66917. },
  66918. set: function (color) {
  66919. this._loadingDivBackgroundColor = color;
  66920. if (!this._loadingDiv) {
  66921. return;
  66922. }
  66923. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66924. },
  66925. enumerable: true,
  66926. configurable: true
  66927. });
  66928. return DefaultLoadingScreen;
  66929. }());
  66930. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66931. })(BABYLON || (BABYLON = {}));
  66932. //# sourceMappingURL=babylon.loadingScreen.js.map
  66933. var BABYLON;
  66934. (function (BABYLON) {
  66935. var SceneLoaderProgressEvent = /** @class */ (function () {
  66936. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66937. this.lengthComputable = lengthComputable;
  66938. this.loaded = loaded;
  66939. this.total = total;
  66940. }
  66941. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66942. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66943. };
  66944. return SceneLoaderProgressEvent;
  66945. }());
  66946. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66947. var SceneLoader = /** @class */ (function () {
  66948. function SceneLoader() {
  66949. }
  66950. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66951. get: function () {
  66952. return 0;
  66953. },
  66954. enumerable: true,
  66955. configurable: true
  66956. });
  66957. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66958. get: function () {
  66959. return 1;
  66960. },
  66961. enumerable: true,
  66962. configurable: true
  66963. });
  66964. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66965. get: function () {
  66966. return 2;
  66967. },
  66968. enumerable: true,
  66969. configurable: true
  66970. });
  66971. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66972. get: function () {
  66973. return 3;
  66974. },
  66975. enumerable: true,
  66976. configurable: true
  66977. });
  66978. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66979. get: function () {
  66980. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66981. },
  66982. set: function (value) {
  66983. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66984. },
  66985. enumerable: true,
  66986. configurable: true
  66987. });
  66988. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66989. get: function () {
  66990. return SceneLoader._ShowLoadingScreen;
  66991. },
  66992. set: function (value) {
  66993. SceneLoader._ShowLoadingScreen = value;
  66994. },
  66995. enumerable: true,
  66996. configurable: true
  66997. });
  66998. Object.defineProperty(SceneLoader, "loggingLevel", {
  66999. get: function () {
  67000. return SceneLoader._loggingLevel;
  67001. },
  67002. set: function (value) {
  67003. SceneLoader._loggingLevel = value;
  67004. },
  67005. enumerable: true,
  67006. configurable: true
  67007. });
  67008. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67009. get: function () {
  67010. return SceneLoader._CleanBoneMatrixWeights;
  67011. },
  67012. set: function (value) {
  67013. SceneLoader._CleanBoneMatrixWeights = value;
  67014. },
  67015. enumerable: true,
  67016. configurable: true
  67017. });
  67018. SceneLoader._getDefaultPlugin = function () {
  67019. return SceneLoader._registeredPlugins[".babylon"];
  67020. };
  67021. SceneLoader._getPluginForExtension = function (extension) {
  67022. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67023. if (registeredPlugin) {
  67024. return registeredPlugin;
  67025. }
  67026. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  67027. return SceneLoader._getDefaultPlugin();
  67028. };
  67029. SceneLoader._getPluginForDirectLoad = function (data) {
  67030. for (var extension in SceneLoader._registeredPlugins) {
  67031. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67032. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67033. return SceneLoader._registeredPlugins[extension];
  67034. }
  67035. }
  67036. return SceneLoader._getDefaultPlugin();
  67037. };
  67038. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67039. if (sceneFilename.name) {
  67040. sceneFilename = sceneFilename.name;
  67041. }
  67042. var queryStringPosition = sceneFilename.indexOf("?");
  67043. if (queryStringPosition !== -1) {
  67044. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67045. }
  67046. var dotPosition = sceneFilename.lastIndexOf(".");
  67047. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67048. return SceneLoader._getPluginForExtension(extension);
  67049. };
  67050. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67051. SceneLoader._getDirectLoad = function (sceneFilename) {
  67052. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67053. return sceneFilename.substr(5);
  67054. }
  67055. return null;
  67056. };
  67057. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67058. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67059. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67060. var plugin;
  67061. if (registeredPlugin.plugin.createPlugin) {
  67062. plugin = registeredPlugin.plugin.createPlugin();
  67063. }
  67064. else {
  67065. plugin = registeredPlugin.plugin;
  67066. }
  67067. var useArrayBuffer = registeredPlugin.isBinary;
  67068. var database;
  67069. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67070. var dataCallback = function (data, responseURL) {
  67071. if (scene.isDisposed) {
  67072. onError("Scene has been disposed");
  67073. return;
  67074. }
  67075. scene.database = database;
  67076. onSuccess(plugin, data, responseURL);
  67077. };
  67078. var request = null;
  67079. var pluginDisposed = false;
  67080. var onDisposeObservable = plugin.onDisposeObservable;
  67081. if (onDisposeObservable) {
  67082. onDisposeObservable.add(function () {
  67083. pluginDisposed = true;
  67084. if (request) {
  67085. request.abort();
  67086. request = null;
  67087. }
  67088. onDispose();
  67089. });
  67090. }
  67091. var manifestChecked = function () {
  67092. if (pluginDisposed) {
  67093. return;
  67094. }
  67095. var url = rootUrl + sceneFilename;
  67096. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67097. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67098. } : undefined, database, useArrayBuffer, function (request, exception) {
  67099. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67100. });
  67101. };
  67102. if (directLoad) {
  67103. dataCallback(directLoad);
  67104. return plugin;
  67105. }
  67106. if (rootUrl.indexOf("file:") === -1) {
  67107. var engine = scene.getEngine();
  67108. var canUseOfflineSupport = engine.enableOfflineSupport;
  67109. if (canUseOfflineSupport) {
  67110. // Also check for exceptions
  67111. var exceptionFound = false;
  67112. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67113. var regex = _a[_i];
  67114. if (regex.test(rootUrl + sceneFilename)) {
  67115. exceptionFound = true;
  67116. break;
  67117. }
  67118. }
  67119. canUseOfflineSupport = !exceptionFound;
  67120. }
  67121. if (canUseOfflineSupport) {
  67122. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67123. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67124. }
  67125. else {
  67126. manifestChecked();
  67127. }
  67128. }
  67129. // Loading file from disk via input file or drag'n'drop
  67130. else {
  67131. var fileOrString = sceneFilename;
  67132. if (fileOrString.name) { // File
  67133. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67134. }
  67135. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67136. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67137. }
  67138. else {
  67139. onError("Unable to find file named " + sceneFilename);
  67140. }
  67141. }
  67142. return plugin;
  67143. };
  67144. // Public functions
  67145. SceneLoader.GetPluginForExtension = function (extension) {
  67146. return SceneLoader._getPluginForExtension(extension).plugin;
  67147. };
  67148. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67149. return !!SceneLoader._registeredPlugins[extension];
  67150. };
  67151. SceneLoader.RegisterPlugin = function (plugin) {
  67152. if (typeof plugin.extensions === "string") {
  67153. var extension = plugin.extensions;
  67154. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67155. plugin: plugin,
  67156. isBinary: false
  67157. };
  67158. }
  67159. else {
  67160. var extensions = plugin.extensions;
  67161. Object.keys(extensions).forEach(function (extension) {
  67162. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67163. plugin: plugin,
  67164. isBinary: extensions[extension].isBinary
  67165. };
  67166. });
  67167. }
  67168. };
  67169. /**
  67170. * Import meshes into a scene
  67171. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67172. * @param rootUrl a string that defines the root url for scene and resources
  67173. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67174. * @param scene the instance of BABYLON.Scene to append to
  67175. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67176. * @param onProgress a callback with a progress event for each file being loaded
  67177. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67178. * @param pluginExtension the extension used to determine the plugin
  67179. * @returns The loaded plugin
  67180. */
  67181. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67182. if (onSuccess === void 0) { onSuccess = null; }
  67183. if (onProgress === void 0) { onProgress = null; }
  67184. if (onError === void 0) { onError = null; }
  67185. if (pluginExtension === void 0) { pluginExtension = null; }
  67186. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67187. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67188. return null;
  67189. }
  67190. var loadingToken = {};
  67191. scene._addPendingData(loadingToken);
  67192. var disposeHandler = function () {
  67193. scene._removePendingData(loadingToken);
  67194. };
  67195. var errorHandler = function (message, exception) {
  67196. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67197. if (onError) {
  67198. onError(scene, errorMessage, exception);
  67199. }
  67200. else {
  67201. BABYLON.Tools.Error(errorMessage);
  67202. // should the exception be thrown?
  67203. }
  67204. disposeHandler();
  67205. };
  67206. var progressHandler = onProgress ? function (event) {
  67207. try {
  67208. onProgress(event);
  67209. }
  67210. catch (e) {
  67211. errorHandler("Error in onProgress callback", e);
  67212. }
  67213. } : undefined;
  67214. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67215. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67216. if (onSuccess) {
  67217. try {
  67218. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67219. }
  67220. catch (e) {
  67221. errorHandler("Error in onSuccess callback", e);
  67222. }
  67223. }
  67224. scene._removePendingData(loadingToken);
  67225. };
  67226. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67227. if (plugin.rewriteRootURL) {
  67228. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67229. }
  67230. if (sceneFilename === "") {
  67231. if (sceneFilename === "") {
  67232. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67233. }
  67234. }
  67235. if (plugin.importMesh) {
  67236. var syncedPlugin = plugin;
  67237. var meshes = new Array();
  67238. var particleSystems = new Array();
  67239. var skeletons = new Array();
  67240. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67241. return;
  67242. }
  67243. scene.loadingPluginName = plugin.name;
  67244. successHandler(meshes, particleSystems, skeletons, []);
  67245. }
  67246. else {
  67247. var asyncedPlugin = plugin;
  67248. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67249. scene.loadingPluginName = plugin.name;
  67250. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67251. }).catch(function (error) {
  67252. errorHandler(error.message, error);
  67253. });
  67254. }
  67255. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67256. };
  67257. /**
  67258. * Import meshes into a scene
  67259. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67260. * @param rootUrl a string that defines the root url for scene and resources
  67261. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67262. * @param scene the instance of BABYLON.Scene to append to
  67263. * @param onProgress a callback with a progress event for each file being loaded
  67264. * @param pluginExtension the extension used to determine the plugin
  67265. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67266. */
  67267. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67268. if (onProgress === void 0) { onProgress = null; }
  67269. if (pluginExtension === void 0) { pluginExtension = null; }
  67270. return new Promise(function (resolve, reject) {
  67271. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67272. resolve({
  67273. meshes: meshes,
  67274. particleSystems: particleSystems,
  67275. skeletons: skeletons,
  67276. animationGroups: animationGroups
  67277. });
  67278. }, onProgress, function (scene, message, exception) {
  67279. reject(exception || new Error(message));
  67280. }, pluginExtension);
  67281. });
  67282. };
  67283. /**
  67284. * Load a scene
  67285. * @param rootUrl a string that defines the root url for scene and resources
  67286. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67287. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67288. * @param onSuccess a callback with the scene when import succeeds
  67289. * @param onProgress a callback with a progress event for each file being loaded
  67290. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67291. * @param pluginExtension the extension used to determine the plugin
  67292. * @returns The loaded plugin
  67293. */
  67294. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67295. if (onSuccess === void 0) { onSuccess = null; }
  67296. if (onProgress === void 0) { onProgress = null; }
  67297. if (onError === void 0) { onError = null; }
  67298. if (pluginExtension === void 0) { pluginExtension = null; }
  67299. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67300. };
  67301. /**
  67302. * Load a scene
  67303. * @param rootUrl a string that defines the root url for scene and resources
  67304. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67305. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67306. * @param onProgress a callback with a progress event for each file being loaded
  67307. * @param pluginExtension the extension used to determine the plugin
  67308. * @returns The loaded scene
  67309. */
  67310. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67311. if (onProgress === void 0) { onProgress = null; }
  67312. if (pluginExtension === void 0) { pluginExtension = null; }
  67313. return new Promise(function (resolve, reject) {
  67314. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67315. resolve(scene);
  67316. }, onProgress, function (scene, message, exception) {
  67317. reject(exception || new Error(message));
  67318. }, pluginExtension);
  67319. });
  67320. };
  67321. /**
  67322. * Append a scene
  67323. * @param rootUrl a string that defines the root url for scene and resources
  67324. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67325. * @param scene is the instance of BABYLON.Scene to append to
  67326. * @param onSuccess a callback with the scene when import succeeds
  67327. * @param onProgress a callback with a progress event for each file being loaded
  67328. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67329. * @param pluginExtension the extension used to determine the plugin
  67330. * @returns The loaded plugin
  67331. */
  67332. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67333. if (onSuccess === void 0) { onSuccess = null; }
  67334. if (onProgress === void 0) { onProgress = null; }
  67335. if (onError === void 0) { onError = null; }
  67336. if (pluginExtension === void 0) { pluginExtension = null; }
  67337. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67338. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67339. return null;
  67340. }
  67341. if (SceneLoader.ShowLoadingScreen) {
  67342. scene.getEngine().displayLoadingUI();
  67343. }
  67344. var loadingToken = {};
  67345. scene._addPendingData(loadingToken);
  67346. var disposeHandler = function () {
  67347. scene._removePendingData(loadingToken);
  67348. scene.getEngine().hideLoadingUI();
  67349. };
  67350. var errorHandler = function (message, exception) {
  67351. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67352. if (onError) {
  67353. onError(scene, errorMessage, exception);
  67354. }
  67355. else {
  67356. BABYLON.Tools.Error(errorMessage);
  67357. // should the exception be thrown?
  67358. }
  67359. disposeHandler();
  67360. };
  67361. var progressHandler = onProgress ? function (event) {
  67362. try {
  67363. onProgress(event);
  67364. }
  67365. catch (e) {
  67366. errorHandler("Error in onProgress callback", e);
  67367. }
  67368. } : undefined;
  67369. var successHandler = function () {
  67370. if (onSuccess) {
  67371. try {
  67372. onSuccess(scene);
  67373. }
  67374. catch (e) {
  67375. errorHandler("Error in onSuccess callback", e);
  67376. }
  67377. }
  67378. scene._removePendingData(loadingToken);
  67379. };
  67380. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67381. if (sceneFilename === "") {
  67382. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67383. }
  67384. if (plugin.load) {
  67385. var syncedPlugin = plugin;
  67386. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67387. return;
  67388. }
  67389. scene.loadingPluginName = plugin.name;
  67390. successHandler();
  67391. }
  67392. else {
  67393. var asyncedPlugin = plugin;
  67394. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67395. scene.loadingPluginName = plugin.name;
  67396. successHandler();
  67397. }).catch(function (error) {
  67398. errorHandler(error.message, error);
  67399. });
  67400. }
  67401. if (SceneLoader.ShowLoadingScreen) {
  67402. scene.executeWhenReady(function () {
  67403. scene.getEngine().hideLoadingUI();
  67404. });
  67405. }
  67406. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67407. };
  67408. /**
  67409. * Append a scene
  67410. * @param rootUrl a string that defines the root url for scene and resources
  67411. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67412. * @param scene is the instance of BABYLON.Scene to append to
  67413. * @param onProgress a callback with a progress event for each file being loaded
  67414. * @param pluginExtension the extension used to determine the plugin
  67415. * @returns The given scene
  67416. */
  67417. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67418. if (onProgress === void 0) { onProgress = null; }
  67419. if (pluginExtension === void 0) { pluginExtension = null; }
  67420. return new Promise(function (resolve, reject) {
  67421. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67422. resolve(scene);
  67423. }, onProgress, function (scene, message, exception) {
  67424. reject(exception || new Error(message));
  67425. }, pluginExtension);
  67426. });
  67427. };
  67428. /**
  67429. * Load a scene into an asset container
  67430. * @param rootUrl a string that defines the root url for scene and resources
  67431. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67432. * @param scene is the instance of BABYLON.Scene to append to
  67433. * @param onSuccess a callback with the scene when import succeeds
  67434. * @param onProgress a callback with a progress event for each file being loaded
  67435. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67436. * @param pluginExtension the extension used to determine the plugin
  67437. * @returns The loaded plugin
  67438. */
  67439. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67440. if (onSuccess === void 0) { onSuccess = null; }
  67441. if (onProgress === void 0) { onProgress = null; }
  67442. if (onError === void 0) { onError = null; }
  67443. if (pluginExtension === void 0) { pluginExtension = null; }
  67444. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67445. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67446. return null;
  67447. }
  67448. var loadingToken = {};
  67449. scene._addPendingData(loadingToken);
  67450. var disposeHandler = function () {
  67451. scene._removePendingData(loadingToken);
  67452. };
  67453. var errorHandler = function (message, exception) {
  67454. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67455. if (onError) {
  67456. onError(scene, errorMessage, exception);
  67457. }
  67458. else {
  67459. BABYLON.Tools.Error(errorMessage);
  67460. // should the exception be thrown?
  67461. }
  67462. disposeHandler();
  67463. };
  67464. var progressHandler = onProgress ? function (event) {
  67465. try {
  67466. onProgress(event);
  67467. }
  67468. catch (e) {
  67469. errorHandler("Error in onProgress callback", e);
  67470. }
  67471. } : undefined;
  67472. var successHandler = function (assets) {
  67473. if (onSuccess) {
  67474. try {
  67475. onSuccess(assets);
  67476. }
  67477. catch (e) {
  67478. errorHandler("Error in onSuccess callback", e);
  67479. }
  67480. }
  67481. scene._removePendingData(loadingToken);
  67482. };
  67483. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67484. if (plugin.loadAssetContainer) {
  67485. var syncedPlugin = plugin;
  67486. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67487. if (!assetContainer) {
  67488. return;
  67489. }
  67490. scene.loadingPluginName = plugin.name;
  67491. successHandler(assetContainer);
  67492. }
  67493. else if (plugin.loadAssetContainerAsync) {
  67494. var asyncedPlugin = plugin;
  67495. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67496. scene.loadingPluginName = plugin.name;
  67497. successHandler(assetContainer);
  67498. }).catch(function (error) {
  67499. errorHandler(error.message, error);
  67500. });
  67501. }
  67502. else {
  67503. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67504. }
  67505. if (SceneLoader.ShowLoadingScreen) {
  67506. scene.executeWhenReady(function () {
  67507. scene.getEngine().hideLoadingUI();
  67508. });
  67509. }
  67510. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67511. };
  67512. /**
  67513. * Load a scene into an asset container
  67514. * @param rootUrl a string that defines the root url for scene and resources
  67515. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67516. * @param scene is the instance of BABYLON.Scene to append to
  67517. * @param onProgress a callback with a progress event for each file being loaded
  67518. * @param pluginExtension the extension used to determine the plugin
  67519. * @returns The loaded asset container
  67520. */
  67521. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67522. if (onProgress === void 0) { onProgress = null; }
  67523. if (pluginExtension === void 0) { pluginExtension = null; }
  67524. return new Promise(function (resolve, reject) {
  67525. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67526. resolve(assetContainer);
  67527. }, onProgress, function (scene, message, exception) {
  67528. reject(exception || new Error(message));
  67529. }, pluginExtension);
  67530. });
  67531. };
  67532. // Flags
  67533. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67534. SceneLoader._ShowLoadingScreen = true;
  67535. SceneLoader._CleanBoneMatrixWeights = false;
  67536. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67537. // Members
  67538. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67539. SceneLoader._registeredPlugins = {};
  67540. return SceneLoader;
  67541. }());
  67542. BABYLON.SceneLoader = SceneLoader;
  67543. ;
  67544. })(BABYLON || (BABYLON = {}));
  67545. //# sourceMappingURL=babylon.sceneLoader.js.map
  67546. var BABYLON;
  67547. (function (BABYLON) {
  67548. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67549. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67550. var parsedMaterial = parsedData.materials[index];
  67551. if (parsedMaterial.id === id) {
  67552. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67553. }
  67554. }
  67555. return null;
  67556. };
  67557. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67558. for (var i in names) {
  67559. if (mesh.name === names[i]) {
  67560. hierarchyIds.push(mesh.id);
  67561. return true;
  67562. }
  67563. }
  67564. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67565. hierarchyIds.push(mesh.id);
  67566. return true;
  67567. }
  67568. return false;
  67569. };
  67570. var logOperation = function (operation, producer) {
  67571. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67572. };
  67573. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67574. if (addToScene === void 0) { addToScene = false; }
  67575. var container = new BABYLON.AssetContainer(scene);
  67576. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67577. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67578. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67579. // and avoid problems with multiple concurrent .babylon loads.
  67580. var log = "importScene has failed JSON parse";
  67581. try {
  67582. var parsedData = JSON.parse(data);
  67583. log = "";
  67584. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67585. var index;
  67586. var cache;
  67587. // Lights
  67588. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67589. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67590. var parsedLight = parsedData.lights[index];
  67591. var light = BABYLON.Light.Parse(parsedLight, scene);
  67592. if (light) {
  67593. container.lights.push(light);
  67594. log += (index === 0 ? "\n\tLights:" : "");
  67595. log += "\n\t\t" + light.toString(fullDetails);
  67596. }
  67597. }
  67598. }
  67599. // Animations
  67600. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67601. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67602. var parsedAnimation = parsedData.animations[index];
  67603. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67604. scene.animations.push(animation);
  67605. container.animations.push(animation);
  67606. log += (index === 0 ? "\n\tAnimations:" : "");
  67607. log += "\n\t\t" + animation.toString(fullDetails);
  67608. }
  67609. }
  67610. // Materials
  67611. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67612. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67613. var parsedMaterial = parsedData.materials[index];
  67614. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67615. container.materials.push(mat);
  67616. log += (index === 0 ? "\n\tMaterials:" : "");
  67617. log += "\n\t\t" + mat.toString(fullDetails);
  67618. }
  67619. }
  67620. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67621. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67622. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67623. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67624. container.multiMaterials.push(mmat);
  67625. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67626. log += "\n\t\t" + mmat.toString(fullDetails);
  67627. }
  67628. }
  67629. // Morph targets
  67630. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67631. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67632. var managerData = _a[_i];
  67633. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67634. }
  67635. }
  67636. // Skeletons
  67637. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67638. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67639. var parsedSkeleton = parsedData.skeletons[index];
  67640. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67641. container.skeletons.push(skeleton);
  67642. log += (index === 0 ? "\n\tSkeletons:" : "");
  67643. log += "\n\t\t" + skeleton.toString(fullDetails);
  67644. }
  67645. }
  67646. // Geometries
  67647. var geometries = parsedData.geometries;
  67648. if (geometries !== undefined && geometries !== null) {
  67649. var addedGeometry = new Array();
  67650. // Boxes
  67651. var boxes = geometries.boxes;
  67652. if (boxes !== undefined && boxes !== null) {
  67653. for (index = 0, cache = boxes.length; index < cache; index++) {
  67654. var parsedBox = boxes[index];
  67655. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67656. }
  67657. }
  67658. // Spheres
  67659. var spheres = geometries.spheres;
  67660. if (spheres !== undefined && spheres !== null) {
  67661. for (index = 0, cache = spheres.length; index < cache; index++) {
  67662. var parsedSphere = spheres[index];
  67663. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67664. }
  67665. }
  67666. // Cylinders
  67667. var cylinders = geometries.cylinders;
  67668. if (cylinders !== undefined && cylinders !== null) {
  67669. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67670. var parsedCylinder = cylinders[index];
  67671. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67672. }
  67673. }
  67674. // Toruses
  67675. var toruses = geometries.toruses;
  67676. if (toruses !== undefined && toruses !== null) {
  67677. for (index = 0, cache = toruses.length; index < cache; index++) {
  67678. var parsedTorus = toruses[index];
  67679. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67680. }
  67681. }
  67682. // Grounds
  67683. var grounds = geometries.grounds;
  67684. if (grounds !== undefined && grounds !== null) {
  67685. for (index = 0, cache = grounds.length; index < cache; index++) {
  67686. var parsedGround = grounds[index];
  67687. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67688. }
  67689. }
  67690. // Planes
  67691. var planes = geometries.planes;
  67692. if (planes !== undefined && planes !== null) {
  67693. for (index = 0, cache = planes.length; index < cache; index++) {
  67694. var parsedPlane = planes[index];
  67695. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67696. }
  67697. }
  67698. // TorusKnots
  67699. var torusKnots = geometries.torusKnots;
  67700. if (torusKnots !== undefined && torusKnots !== null) {
  67701. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67702. var parsedTorusKnot = torusKnots[index];
  67703. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67704. }
  67705. }
  67706. // VertexData
  67707. var vertexData = geometries.vertexData;
  67708. if (vertexData !== undefined && vertexData !== null) {
  67709. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67710. var parsedVertexData = vertexData[index];
  67711. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67712. }
  67713. }
  67714. addedGeometry.forEach(function (g) {
  67715. if (g) {
  67716. container.geometries.push(g);
  67717. }
  67718. });
  67719. }
  67720. // Transform nodes
  67721. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67722. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67723. var parsedTransformNode = parsedData.transformNodes[index];
  67724. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67725. container.transformNodes.push(node);
  67726. }
  67727. }
  67728. // Meshes
  67729. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67730. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67731. var parsedMesh = parsedData.meshes[index];
  67732. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67733. container.meshes.push(mesh);
  67734. log += (index === 0 ? "\n\tMeshes:" : "");
  67735. log += "\n\t\t" + mesh.toString(fullDetails);
  67736. }
  67737. }
  67738. // Cameras
  67739. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67740. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67741. var parsedCamera = parsedData.cameras[index];
  67742. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67743. container.cameras.push(camera);
  67744. log += (index === 0 ? "\n\tCameras:" : "");
  67745. log += "\n\t\t" + camera.toString(fullDetails);
  67746. }
  67747. }
  67748. // Browsing all the graph to connect the dots
  67749. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67750. var camera = scene.cameras[index];
  67751. if (camera._waitingParentId) {
  67752. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67753. camera._waitingParentId = null;
  67754. }
  67755. }
  67756. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67757. var light_1 = scene.lights[index];
  67758. if (light_1 && light_1._waitingParentId) {
  67759. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67760. light_1._waitingParentId = null;
  67761. }
  67762. }
  67763. // Sounds
  67764. // TODO: add sound
  67765. var loadedSounds = [];
  67766. var loadedSound;
  67767. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67768. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67769. var parsedSound = parsedData.sounds[index];
  67770. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67771. if (!parsedSound.url)
  67772. parsedSound.url = parsedSound.name;
  67773. if (!loadedSounds[parsedSound.url]) {
  67774. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67775. loadedSounds[parsedSound.url] = loadedSound;
  67776. container.sounds.push(loadedSound);
  67777. }
  67778. else {
  67779. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67780. }
  67781. }
  67782. else {
  67783. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67784. }
  67785. }
  67786. }
  67787. loadedSounds = [];
  67788. // Connect parents & children and parse actions
  67789. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67790. var transformNode = scene.transformNodes[index];
  67791. if (transformNode._waitingParentId) {
  67792. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67793. transformNode._waitingParentId = null;
  67794. }
  67795. }
  67796. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67797. var mesh = scene.meshes[index];
  67798. if (mesh._waitingParentId) {
  67799. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67800. mesh._waitingParentId = null;
  67801. }
  67802. if (mesh._waitingActions) {
  67803. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67804. mesh._waitingActions = null;
  67805. }
  67806. }
  67807. // freeze world matrix application
  67808. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67809. var currentMesh = scene.meshes[index];
  67810. if (currentMesh._waitingFreezeWorldMatrix) {
  67811. currentMesh.freezeWorldMatrix();
  67812. currentMesh._waitingFreezeWorldMatrix = null;
  67813. }
  67814. else {
  67815. currentMesh.computeWorldMatrix(true);
  67816. }
  67817. }
  67818. // Particles Systems
  67819. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67820. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67821. var parsedParticleSystem = parsedData.particleSystems[index];
  67822. if (parsedParticleSystem.activeParticleCount) {
  67823. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67824. container.particleSystems.push(ps);
  67825. }
  67826. else {
  67827. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67828. container.particleSystems.push(ps);
  67829. }
  67830. }
  67831. }
  67832. // Lens flares
  67833. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67834. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67835. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67836. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67837. container.lensFlareSystems.push(lf);
  67838. }
  67839. }
  67840. // Shadows
  67841. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67842. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67843. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67844. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67845. container.shadowGenerators.push(sg);
  67846. }
  67847. }
  67848. // Lights exclusions / inclusions
  67849. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67850. var light_2 = scene.lights[index];
  67851. // Excluded check
  67852. if (light_2._excludedMeshesIds.length > 0) {
  67853. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67854. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67855. if (excludedMesh) {
  67856. light_2.excludedMeshes.push(excludedMesh);
  67857. }
  67858. }
  67859. light_2._excludedMeshesIds = [];
  67860. }
  67861. // Included check
  67862. if (light_2._includedOnlyMeshesIds.length > 0) {
  67863. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67864. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67865. if (includedOnlyMesh) {
  67866. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67867. }
  67868. }
  67869. light_2._includedOnlyMeshesIds = [];
  67870. }
  67871. }
  67872. // Effect layers
  67873. if (parsedData.effectLayers) {
  67874. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67875. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67876. container.effectLayers.push(effectLayer);
  67877. }
  67878. }
  67879. // Actions (scene)
  67880. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67881. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67882. }
  67883. if (!addToScene) {
  67884. container.removeAllFromScene();
  67885. }
  67886. }
  67887. catch (err) {
  67888. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67889. if (onError) {
  67890. onError(msg, err);
  67891. }
  67892. else {
  67893. BABYLON.Tools.Log(msg);
  67894. throw err;
  67895. }
  67896. }
  67897. finally {
  67898. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67899. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67900. }
  67901. }
  67902. return container;
  67903. };
  67904. BABYLON.SceneLoader.RegisterPlugin({
  67905. name: "babylon.js",
  67906. extensions: ".babylon",
  67907. canDirectLoad: function (data) {
  67908. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67909. return true;
  67910. }
  67911. return false;
  67912. },
  67913. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67914. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67915. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67916. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67917. // and avoid problems with multiple concurrent .babylon loads.
  67918. var log = "importMesh has failed JSON parse";
  67919. try {
  67920. var parsedData = JSON.parse(data);
  67921. log = "";
  67922. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67923. if (!meshesNames) {
  67924. meshesNames = null;
  67925. }
  67926. else if (!Array.isArray(meshesNames)) {
  67927. meshesNames = [meshesNames];
  67928. }
  67929. var hierarchyIds = new Array();
  67930. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67931. var loadedSkeletonsIds = [];
  67932. var loadedMaterialsIds = [];
  67933. var index;
  67934. var cache;
  67935. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67936. var parsedMesh = parsedData.meshes[index];
  67937. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67938. if (meshesNames !== null) {
  67939. // Remove found mesh name from list.
  67940. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67941. }
  67942. //Geometry?
  67943. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67944. //does the file contain geometries?
  67945. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67946. //find the correct geometry and add it to the scene
  67947. var found = false;
  67948. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67949. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67950. return;
  67951. }
  67952. else {
  67953. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67954. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67955. switch (geometryType) {
  67956. case "boxes":
  67957. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67958. break;
  67959. case "spheres":
  67960. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67961. break;
  67962. case "cylinders":
  67963. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67964. break;
  67965. case "toruses":
  67966. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67967. break;
  67968. case "grounds":
  67969. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67970. break;
  67971. case "planes":
  67972. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67973. break;
  67974. case "torusKnots":
  67975. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67976. break;
  67977. case "vertexData":
  67978. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67979. break;
  67980. }
  67981. found = true;
  67982. }
  67983. });
  67984. }
  67985. });
  67986. if (found === false) {
  67987. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67988. }
  67989. }
  67990. }
  67991. // Material ?
  67992. if (parsedMesh.materialId) {
  67993. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67994. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67995. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67996. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67997. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67998. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67999. var subMatId = parsedMultiMaterial.materials[matIndex];
  68000. loadedMaterialsIds.push(subMatId);
  68001. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68002. if (mat) {
  68003. log += "\n\tMaterial " + mat.toString(fullDetails);
  68004. }
  68005. }
  68006. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68007. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68008. if (mmat) {
  68009. materialFound = true;
  68010. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68011. }
  68012. break;
  68013. }
  68014. }
  68015. }
  68016. if (materialFound === false) {
  68017. loadedMaterialsIds.push(parsedMesh.materialId);
  68018. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68019. if (!mat) {
  68020. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68021. }
  68022. else {
  68023. log += "\n\tMaterial " + mat.toString(fullDetails);
  68024. }
  68025. }
  68026. }
  68027. // Skeleton ?
  68028. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68029. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68030. if (skeletonAlreadyLoaded === false) {
  68031. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68032. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68033. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68034. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68035. skeletons.push(skeleton);
  68036. loadedSkeletonsIds.push(parsedSkeleton.id);
  68037. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68038. }
  68039. }
  68040. }
  68041. }
  68042. // Morph targets ?
  68043. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68044. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68045. var managerData = _a[_i];
  68046. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68047. }
  68048. }
  68049. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68050. meshes.push(mesh);
  68051. log += "\n\tMesh " + mesh.toString(fullDetails);
  68052. }
  68053. }
  68054. // Connecting parents
  68055. var currentMesh;
  68056. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68057. currentMesh = scene.meshes[index];
  68058. if (currentMesh._waitingParentId) {
  68059. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68060. currentMesh._waitingParentId = null;
  68061. }
  68062. }
  68063. // freeze and compute world matrix application
  68064. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68065. currentMesh = scene.meshes[index];
  68066. if (currentMesh._waitingFreezeWorldMatrix) {
  68067. currentMesh.freezeWorldMatrix();
  68068. currentMesh._waitingFreezeWorldMatrix = null;
  68069. }
  68070. else {
  68071. currentMesh.computeWorldMatrix(true);
  68072. }
  68073. }
  68074. }
  68075. // Particles
  68076. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68077. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68078. var parsedParticleSystem = parsedData.particleSystems[index];
  68079. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68080. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68081. }
  68082. }
  68083. }
  68084. return true;
  68085. }
  68086. catch (err) {
  68087. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68088. if (onError) {
  68089. onError(msg, err);
  68090. }
  68091. else {
  68092. BABYLON.Tools.Log(msg);
  68093. throw err;
  68094. }
  68095. }
  68096. finally {
  68097. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68098. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68099. }
  68100. }
  68101. return false;
  68102. },
  68103. load: function (scene, data, rootUrl, onError) {
  68104. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68105. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68106. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68107. // and avoid problems with multiple concurrent .babylon loads.
  68108. var log = "importScene has failed JSON parse";
  68109. try {
  68110. var parsedData = JSON.parse(data);
  68111. log = "";
  68112. // Scene
  68113. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68114. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68115. }
  68116. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68117. scene.autoClear = parsedData.autoClear;
  68118. }
  68119. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68120. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68121. }
  68122. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68123. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68124. }
  68125. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68126. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68127. }
  68128. // Fog
  68129. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68130. scene.fogMode = parsedData.fogMode;
  68131. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68132. scene.fogStart = parsedData.fogStart;
  68133. scene.fogEnd = parsedData.fogEnd;
  68134. scene.fogDensity = parsedData.fogDensity;
  68135. log += "\tFog mode for scene: ";
  68136. switch (scene.fogMode) {
  68137. // getters not compiling, so using hardcoded
  68138. case 1:
  68139. log += "exp\n";
  68140. break;
  68141. case 2:
  68142. log += "exp2\n";
  68143. break;
  68144. case 3:
  68145. log += "linear\n";
  68146. break;
  68147. }
  68148. }
  68149. //Physics
  68150. if (parsedData.physicsEnabled) {
  68151. var physicsPlugin;
  68152. if (parsedData.physicsEngine === "cannon") {
  68153. physicsPlugin = new BABYLON.CannonJSPlugin();
  68154. }
  68155. else if (parsedData.physicsEngine === "oimo") {
  68156. physicsPlugin = new BABYLON.OimoJSPlugin();
  68157. }
  68158. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68159. //else - default engine, which is currently oimo
  68160. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68161. scene.enablePhysics(physicsGravity, physicsPlugin);
  68162. }
  68163. // Metadata
  68164. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68165. scene.metadata = parsedData.metadata;
  68166. }
  68167. //collisions, if defined. otherwise, default is true
  68168. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68169. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68170. }
  68171. scene.workerCollisions = !!parsedData.workerCollisions;
  68172. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68173. if (!container) {
  68174. return false;
  68175. }
  68176. if (parsedData.autoAnimate) {
  68177. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68178. }
  68179. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68180. scene.setActiveCameraByID(parsedData.activeCameraID);
  68181. }
  68182. // Environment texture
  68183. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68184. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68185. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68186. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68187. if (parsedData.environmentTextureRotationY) {
  68188. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68189. }
  68190. scene.environmentTexture = hdrTexture;
  68191. }
  68192. else {
  68193. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68194. if (parsedData.environmentTextureRotationY) {
  68195. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68196. }
  68197. scene.environmentTexture = cubeTexture;
  68198. }
  68199. if (parsedData.createDefaultSkybox === true) {
  68200. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68201. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68202. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68203. }
  68204. }
  68205. // Finish
  68206. return true;
  68207. }
  68208. catch (err) {
  68209. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68210. if (onError) {
  68211. onError(msg, err);
  68212. }
  68213. else {
  68214. BABYLON.Tools.Log(msg);
  68215. throw err;
  68216. }
  68217. }
  68218. finally {
  68219. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68220. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68221. }
  68222. }
  68223. return false;
  68224. },
  68225. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68226. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68227. return container;
  68228. }
  68229. });
  68230. })(BABYLON || (BABYLON = {}));
  68231. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68232. var BABYLON;
  68233. (function (BABYLON) {
  68234. var FilesInput = /** @class */ (function () {
  68235. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68236. this.onProcessFileCallback = function () { return true; };
  68237. this._engine = engine;
  68238. this._currentScene = scene;
  68239. this._sceneLoadedCallback = sceneLoadedCallback;
  68240. this._progressCallback = progressCallback;
  68241. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68242. this._textureLoadingCallback = textureLoadingCallback;
  68243. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68244. this._onReloadCallback = onReloadCallback;
  68245. this._errorCallback = errorCallback;
  68246. }
  68247. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68248. var _this = this;
  68249. if (elementToMonitor) {
  68250. this._elementToMonitor = elementToMonitor;
  68251. this._dragEnterHandler = function (e) { _this.drag(e); };
  68252. this._dragOverHandler = function (e) { _this.drag(e); };
  68253. this._dropHandler = function (e) { _this.drop(e); };
  68254. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68255. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68256. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68257. }
  68258. };
  68259. FilesInput.prototype.dispose = function () {
  68260. if (!this._elementToMonitor) {
  68261. return;
  68262. }
  68263. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68264. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68265. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68266. };
  68267. FilesInput.prototype.renderFunction = function () {
  68268. if (this._additionalRenderLoopLogicCallback) {
  68269. this._additionalRenderLoopLogicCallback();
  68270. }
  68271. if (this._currentScene) {
  68272. if (this._textureLoadingCallback) {
  68273. var remaining = this._currentScene.getWaitingItemsCount();
  68274. if (remaining > 0) {
  68275. this._textureLoadingCallback(remaining);
  68276. }
  68277. }
  68278. this._currentScene.render();
  68279. }
  68280. };
  68281. FilesInput.prototype.drag = function (e) {
  68282. e.stopPropagation();
  68283. e.preventDefault();
  68284. };
  68285. FilesInput.prototype.drop = function (eventDrop) {
  68286. eventDrop.stopPropagation();
  68287. eventDrop.preventDefault();
  68288. this.loadFiles(eventDrop);
  68289. };
  68290. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68291. var _this = this;
  68292. var reader = folder.createReader();
  68293. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68294. reader.readEntries(function (entries) {
  68295. remaining.count += entries.length;
  68296. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68297. var entry = entries_1[_i];
  68298. if (entry.isFile) {
  68299. entry.file(function (file) {
  68300. file.correctName = relativePath + file.name;
  68301. files.push(file);
  68302. if (--remaining.count === 0) {
  68303. callback();
  68304. }
  68305. });
  68306. }
  68307. else if (entry.isDirectory) {
  68308. _this._traverseFolder(entry, files, remaining, callback);
  68309. }
  68310. }
  68311. if (--remaining.count) {
  68312. callback();
  68313. }
  68314. });
  68315. };
  68316. FilesInput.prototype._processFiles = function (files) {
  68317. for (var i = 0; i < files.length; i++) {
  68318. var name = files[i].correctName.toLowerCase();
  68319. var extension = name.split('.').pop();
  68320. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68321. continue;
  68322. }
  68323. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68324. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68325. this._sceneFileToLoad = files[i];
  68326. }
  68327. else {
  68328. FilesInput.FilesToLoad[name] = files[i];
  68329. }
  68330. }
  68331. };
  68332. FilesInput.prototype.loadFiles = function (event) {
  68333. var _this = this;
  68334. if (this._startingProcessingFilesCallback)
  68335. this._startingProcessingFilesCallback();
  68336. // Handling data transfer via drag'n'drop
  68337. if (event && event.dataTransfer && event.dataTransfer.files) {
  68338. this._filesToLoad = event.dataTransfer.files;
  68339. }
  68340. // Handling files from input files
  68341. if (event && event.target && event.target.files) {
  68342. this._filesToLoad = event.target.files;
  68343. }
  68344. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68345. var files_1 = new Array();
  68346. var folders = [];
  68347. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68348. for (var i = 0; i < this._filesToLoad.length; i++) {
  68349. var fileToLoad = this._filesToLoad[i];
  68350. var name_1 = fileToLoad.name.toLowerCase();
  68351. var entry = void 0;
  68352. fileToLoad.correctName = name_1;
  68353. if (items) {
  68354. var item = items[i];
  68355. if (item.getAsEntry) {
  68356. entry = item.getAsEntry();
  68357. }
  68358. else if (item.webkitGetAsEntry) {
  68359. entry = item.webkitGetAsEntry();
  68360. }
  68361. }
  68362. if (!entry) {
  68363. files_1.push(fileToLoad);
  68364. }
  68365. else {
  68366. if (entry.isDirectory) {
  68367. folders.push(entry);
  68368. }
  68369. else {
  68370. files_1.push(fileToLoad);
  68371. }
  68372. }
  68373. }
  68374. if (folders.length === 0) {
  68375. this._processFiles(files_1);
  68376. this._processReload();
  68377. }
  68378. else {
  68379. var remaining = { count: folders.length };
  68380. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68381. var folder = folders_1[_i];
  68382. this._traverseFolder(folder, files_1, remaining, function () {
  68383. _this._processFiles(files_1);
  68384. if (remaining.count === 0) {
  68385. _this._processReload();
  68386. }
  68387. });
  68388. }
  68389. }
  68390. }
  68391. };
  68392. FilesInput.prototype._processReload = function () {
  68393. if (this._onReloadCallback) {
  68394. this._onReloadCallback(this._sceneFileToLoad);
  68395. }
  68396. else {
  68397. this.reload();
  68398. }
  68399. };
  68400. FilesInput.prototype.reload = function () {
  68401. var _this = this;
  68402. // If a scene file has been provided
  68403. if (this._sceneFileToLoad) {
  68404. if (this._currentScene) {
  68405. if (BABYLON.Tools.errorsCount > 0) {
  68406. BABYLON.Tools.ClearLogCache();
  68407. }
  68408. this._engine.stopRenderLoop();
  68409. this._currentScene.dispose();
  68410. }
  68411. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68412. if (_this._progressCallback) {
  68413. _this._progressCallback(progress);
  68414. }
  68415. }).then(function (scene) {
  68416. _this._currentScene = scene;
  68417. if (_this._sceneLoadedCallback) {
  68418. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68419. }
  68420. // Wait for textures and shaders to be ready
  68421. _this._currentScene.executeWhenReady(function () {
  68422. _this._engine.runRenderLoop(function () {
  68423. _this.renderFunction();
  68424. });
  68425. });
  68426. }).catch(function (error) {
  68427. if (_this._errorCallback) {
  68428. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68429. }
  68430. });
  68431. }
  68432. else {
  68433. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68434. }
  68435. };
  68436. FilesInput.FilesToLoad = {};
  68437. return FilesInput;
  68438. }());
  68439. BABYLON.FilesInput = FilesInput;
  68440. })(BABYLON || (BABYLON = {}));
  68441. //# sourceMappingURL=babylon.filesInput.js.map
  68442. var BABYLON;
  68443. (function (BABYLON) {
  68444. /**
  68445. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68446. * The underlying implementation relies on an associative array to ensure the best performances.
  68447. * The value can be anything including 'null' but except 'undefined'
  68448. */
  68449. var StringDictionary = /** @class */ (function () {
  68450. function StringDictionary() {
  68451. this._count = 0;
  68452. this._data = {};
  68453. }
  68454. /**
  68455. * This will clear this dictionary and copy the content from the 'source' one.
  68456. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68457. * @param source the dictionary to take the content from and copy to this dictionary
  68458. */
  68459. StringDictionary.prototype.copyFrom = function (source) {
  68460. var _this = this;
  68461. this.clear();
  68462. source.forEach(function (t, v) { return _this.add(t, v); });
  68463. };
  68464. /**
  68465. * Get a value based from its key
  68466. * @param key the given key to get the matching value from
  68467. * @return the value if found, otherwise undefined is returned
  68468. */
  68469. StringDictionary.prototype.get = function (key) {
  68470. var val = this._data[key];
  68471. if (val !== undefined) {
  68472. return val;
  68473. }
  68474. return undefined;
  68475. };
  68476. /**
  68477. * Get a value from its key or add it if it doesn't exist.
  68478. * This method will ensure you that a given key/data will be present in the dictionary.
  68479. * @param key the given key to get the matching value from
  68480. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68481. * The factory will only be invoked if there's no data for the given key.
  68482. * @return the value corresponding to the key.
  68483. */
  68484. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68485. var val = this.get(key);
  68486. if (val !== undefined) {
  68487. return val;
  68488. }
  68489. val = factory(key);
  68490. if (val) {
  68491. this.add(key, val);
  68492. }
  68493. return val;
  68494. };
  68495. /**
  68496. * Get a value from its key if present in the dictionary otherwise add it
  68497. * @param key the key to get the value from
  68498. * @param val if there's no such key/value pair in the dictionary add it with this value
  68499. * @return the value corresponding to the key
  68500. */
  68501. StringDictionary.prototype.getOrAdd = function (key, val) {
  68502. var curVal = this.get(key);
  68503. if (curVal !== undefined) {
  68504. return curVal;
  68505. }
  68506. this.add(key, val);
  68507. return val;
  68508. };
  68509. /**
  68510. * Check if there's a given key in the dictionary
  68511. * @param key the key to check for
  68512. * @return true if the key is present, false otherwise
  68513. */
  68514. StringDictionary.prototype.contains = function (key) {
  68515. return this._data[key] !== undefined;
  68516. };
  68517. /**
  68518. * Add a new key and its corresponding value
  68519. * @param key the key to add
  68520. * @param value the value corresponding to the key
  68521. * @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
  68522. */
  68523. StringDictionary.prototype.add = function (key, value) {
  68524. if (this._data[key] !== undefined) {
  68525. return false;
  68526. }
  68527. this._data[key] = value;
  68528. ++this._count;
  68529. return true;
  68530. };
  68531. StringDictionary.prototype.set = function (key, value) {
  68532. if (this._data[key] === undefined) {
  68533. return false;
  68534. }
  68535. this._data[key] = value;
  68536. return true;
  68537. };
  68538. /**
  68539. * Get the element of the given key and remove it from the dictionary
  68540. * @param key
  68541. */
  68542. StringDictionary.prototype.getAndRemove = function (key) {
  68543. var val = this.get(key);
  68544. if (val !== undefined) {
  68545. delete this._data[key];
  68546. --this._count;
  68547. return val;
  68548. }
  68549. return null;
  68550. };
  68551. /**
  68552. * Remove a key/value from the dictionary.
  68553. * @param key the key to remove
  68554. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68555. */
  68556. StringDictionary.prototype.remove = function (key) {
  68557. if (this.contains(key)) {
  68558. delete this._data[key];
  68559. --this._count;
  68560. return true;
  68561. }
  68562. return false;
  68563. };
  68564. /**
  68565. * Clear the whole content of the dictionary
  68566. */
  68567. StringDictionary.prototype.clear = function () {
  68568. this._data = {};
  68569. this._count = 0;
  68570. };
  68571. Object.defineProperty(StringDictionary.prototype, "count", {
  68572. get: function () {
  68573. return this._count;
  68574. },
  68575. enumerable: true,
  68576. configurable: true
  68577. });
  68578. /**
  68579. * Execute a callback on each key/val of the dictionary.
  68580. * Note that you can remove any element in this dictionary in the callback implementation
  68581. * @param callback the callback to execute on a given key/value pair
  68582. */
  68583. StringDictionary.prototype.forEach = function (callback) {
  68584. for (var cur in this._data) {
  68585. var val = this._data[cur];
  68586. callback(cur, val);
  68587. }
  68588. };
  68589. /**
  68590. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68591. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68592. * Note that you can remove any element in this dictionary in the callback implementation
  68593. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68594. */
  68595. StringDictionary.prototype.first = function (callback) {
  68596. for (var cur in this._data) {
  68597. var val = this._data[cur];
  68598. var res = callback(cur, val);
  68599. if (res) {
  68600. return res;
  68601. }
  68602. }
  68603. return null;
  68604. };
  68605. return StringDictionary;
  68606. }());
  68607. BABYLON.StringDictionary = StringDictionary;
  68608. })(BABYLON || (BABYLON = {}));
  68609. //# sourceMappingURL=babylon.stringDictionary.js.map
  68610. var BABYLON;
  68611. (function (BABYLON) {
  68612. var Tags = /** @class */ (function () {
  68613. function Tags() {
  68614. }
  68615. Tags.EnableFor = function (obj) {
  68616. obj._tags = obj._tags || {};
  68617. obj.hasTags = function () {
  68618. return Tags.HasTags(obj);
  68619. };
  68620. obj.addTags = function (tagsString) {
  68621. return Tags.AddTagsTo(obj, tagsString);
  68622. };
  68623. obj.removeTags = function (tagsString) {
  68624. return Tags.RemoveTagsFrom(obj, tagsString);
  68625. };
  68626. obj.matchesTagsQuery = function (tagsQuery) {
  68627. return Tags.MatchesQuery(obj, tagsQuery);
  68628. };
  68629. };
  68630. Tags.DisableFor = function (obj) {
  68631. delete obj._tags;
  68632. delete obj.hasTags;
  68633. delete obj.addTags;
  68634. delete obj.removeTags;
  68635. delete obj.matchesTagsQuery;
  68636. };
  68637. Tags.HasTags = function (obj) {
  68638. if (!obj._tags) {
  68639. return false;
  68640. }
  68641. return !BABYLON.Tools.IsEmpty(obj._tags);
  68642. };
  68643. Tags.GetTags = function (obj, asString) {
  68644. if (asString === void 0) { asString = true; }
  68645. if (!obj._tags) {
  68646. return null;
  68647. }
  68648. if (asString) {
  68649. var tagsArray = [];
  68650. for (var tag in obj._tags) {
  68651. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68652. tagsArray.push(tag);
  68653. }
  68654. }
  68655. return tagsArray.join(" ");
  68656. }
  68657. else {
  68658. return obj._tags;
  68659. }
  68660. };
  68661. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68662. // a tag cannot start with '||', '&&', and '!'
  68663. // it cannot contain whitespaces
  68664. Tags.AddTagsTo = function (obj, tagsString) {
  68665. if (!tagsString) {
  68666. return;
  68667. }
  68668. if (typeof tagsString !== "string") {
  68669. return;
  68670. }
  68671. var tags = tagsString.split(" ");
  68672. tags.forEach(function (tag, index, array) {
  68673. Tags._AddTagTo(obj, tag);
  68674. });
  68675. };
  68676. Tags._AddTagTo = function (obj, tag) {
  68677. tag = tag.trim();
  68678. if (tag === "" || tag === "true" || tag === "false") {
  68679. return;
  68680. }
  68681. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68682. return;
  68683. }
  68684. Tags.EnableFor(obj);
  68685. obj._tags[tag] = true;
  68686. };
  68687. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68688. if (!Tags.HasTags(obj)) {
  68689. return;
  68690. }
  68691. var tags = tagsString.split(" ");
  68692. for (var t in tags) {
  68693. Tags._RemoveTagFrom(obj, tags[t]);
  68694. }
  68695. };
  68696. Tags._RemoveTagFrom = function (obj, tag) {
  68697. delete obj._tags[tag];
  68698. };
  68699. Tags.MatchesQuery = function (obj, tagsQuery) {
  68700. if (tagsQuery === undefined) {
  68701. return true;
  68702. }
  68703. if (tagsQuery === "") {
  68704. return Tags.HasTags(obj);
  68705. }
  68706. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68707. };
  68708. return Tags;
  68709. }());
  68710. BABYLON.Tags = Tags;
  68711. })(BABYLON || (BABYLON = {}));
  68712. //# sourceMappingURL=babylon.tags.js.map
  68713. var BABYLON;
  68714. (function (BABYLON) {
  68715. /**
  68716. * Class used to evalaute queries containing `and` and `or` operators
  68717. */
  68718. var AndOrNotEvaluator = /** @class */ (function () {
  68719. function AndOrNotEvaluator() {
  68720. }
  68721. /**
  68722. * Evaluate a query
  68723. * @param query defines the query to evaluate
  68724. * @param evaluateCallback defines the callback used to filter result
  68725. * @returns true if the query matches
  68726. */
  68727. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68728. if (!query.match(/\([^\(\)]*\)/g)) {
  68729. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68730. }
  68731. else {
  68732. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68733. // remove parenthesis
  68734. r = r.slice(1, r.length - 1);
  68735. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68736. });
  68737. }
  68738. if (query === "true") {
  68739. return true;
  68740. }
  68741. if (query === "false") {
  68742. return false;
  68743. }
  68744. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68745. };
  68746. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68747. evaluateCallback = evaluateCallback || (function (r) {
  68748. return r === "true" ? true : false;
  68749. });
  68750. var result;
  68751. var or = parenthesisContent.split("||");
  68752. for (var i in or) {
  68753. if (or.hasOwnProperty(i)) {
  68754. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68755. var and = ori.split("&&");
  68756. if (and.length > 1) {
  68757. for (var j = 0; j < and.length; ++j) {
  68758. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68759. if (andj !== "true" && andj !== "false") {
  68760. if (andj[0] === "!") {
  68761. result = !evaluateCallback(andj.substring(1));
  68762. }
  68763. else {
  68764. result = evaluateCallback(andj);
  68765. }
  68766. }
  68767. else {
  68768. result = andj === "true" ? true : false;
  68769. }
  68770. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68771. ori = "false";
  68772. break;
  68773. }
  68774. }
  68775. }
  68776. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68777. result = true;
  68778. break;
  68779. }
  68780. // result equals false (or undefined)
  68781. if (ori !== "true" && ori !== "false") {
  68782. if (ori[0] === "!") {
  68783. result = !evaluateCallback(ori.substring(1));
  68784. }
  68785. else {
  68786. result = evaluateCallback(ori);
  68787. }
  68788. }
  68789. else {
  68790. result = ori === "true" ? true : false;
  68791. }
  68792. }
  68793. }
  68794. // the whole parenthesis scope is replaced by 'true' or 'false'
  68795. return result ? "true" : "false";
  68796. };
  68797. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68798. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68799. // remove whitespaces
  68800. r = r.replace(/[\s]/g, function () { return ""; });
  68801. return r.length % 2 ? "!" : "";
  68802. });
  68803. booleanString = booleanString.trim();
  68804. if (booleanString === "!true") {
  68805. booleanString = "false";
  68806. }
  68807. else if (booleanString === "!false") {
  68808. booleanString = "true";
  68809. }
  68810. return booleanString;
  68811. };
  68812. return AndOrNotEvaluator;
  68813. }());
  68814. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68815. })(BABYLON || (BABYLON = {}));
  68816. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68817. var BABYLON;
  68818. (function (BABYLON) {
  68819. /**
  68820. * Class used to enable access to IndexedDB
  68821. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68822. */
  68823. var Database = /** @class */ (function () {
  68824. /**
  68825. * Creates a new Database
  68826. * @param urlToScene defines the url to load the scene
  68827. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68828. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68829. */
  68830. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68831. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68832. var _this = this;
  68833. // Handling various flavors of prefixed version of IndexedDB
  68834. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68835. this.callbackManifestChecked = callbackManifestChecked;
  68836. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68837. this.db = null;
  68838. this._enableSceneOffline = false;
  68839. this._enableTexturesOffline = false;
  68840. this.manifestVersionFound = 0;
  68841. this.mustUpdateRessources = false;
  68842. this.hasReachedQuota = false;
  68843. if (!Database.IDBStorageEnabled) {
  68844. this.callbackManifestChecked(true);
  68845. }
  68846. else {
  68847. if (disableManifestCheck) {
  68848. this._enableSceneOffline = true;
  68849. this._enableTexturesOffline = true;
  68850. this.manifestVersionFound = 1;
  68851. BABYLON.Tools.SetImmediate(function () {
  68852. _this.callbackManifestChecked(true);
  68853. });
  68854. }
  68855. else {
  68856. this._checkManifestFile();
  68857. }
  68858. }
  68859. }
  68860. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68861. /**
  68862. * Gets a boolean indicating if scene must be saved in the database
  68863. */
  68864. get: function () {
  68865. return this._enableSceneOffline;
  68866. },
  68867. enumerable: true,
  68868. configurable: true
  68869. });
  68870. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68871. /**
  68872. * Gets a boolean indicating if textures must be saved in the database
  68873. */
  68874. get: function () {
  68875. return this._enableTexturesOffline;
  68876. },
  68877. enumerable: true,
  68878. configurable: true
  68879. });
  68880. Database.prototype._checkManifestFile = function () {
  68881. var _this = this;
  68882. var noManifestFile = function () {
  68883. _this._enableSceneOffline = false;
  68884. _this._enableTexturesOffline = false;
  68885. _this.callbackManifestChecked(false);
  68886. };
  68887. var timeStampUsed = false;
  68888. var manifestURL = this.currentSceneUrl + ".manifest";
  68889. var xhr = new XMLHttpRequest();
  68890. if (navigator.onLine) {
  68891. // Adding a timestamp to by-pass browsers' cache
  68892. timeStampUsed = true;
  68893. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68894. }
  68895. xhr.open("GET", manifestURL, true);
  68896. xhr.addEventListener("load", function () {
  68897. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68898. try {
  68899. var manifestFile = JSON.parse(xhr.response);
  68900. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68901. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68902. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68903. _this.manifestVersionFound = manifestFile.version;
  68904. }
  68905. if (_this.callbackManifestChecked) {
  68906. _this.callbackManifestChecked(true);
  68907. }
  68908. }
  68909. catch (ex) {
  68910. noManifestFile();
  68911. }
  68912. }
  68913. else {
  68914. noManifestFile();
  68915. }
  68916. }, false);
  68917. xhr.addEventListener("error", function (event) {
  68918. if (timeStampUsed) {
  68919. timeStampUsed = false;
  68920. // Let's retry without the timeStamp
  68921. // It could fail when coupled with HTML5 Offline API
  68922. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68923. xhr.open("GET", retryManifestURL, true);
  68924. xhr.send();
  68925. }
  68926. else {
  68927. noManifestFile();
  68928. }
  68929. }, false);
  68930. try {
  68931. xhr.send();
  68932. }
  68933. catch (ex) {
  68934. BABYLON.Tools.Error("Error on XHR send request.");
  68935. this.callbackManifestChecked(false);
  68936. }
  68937. };
  68938. /**
  68939. * Open the database and make it available
  68940. * @param successCallback defines the callback to call on success
  68941. * @param errorCallback defines the callback to call on error
  68942. */
  68943. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68944. var _this = this;
  68945. var handleError = function () {
  68946. _this.isSupported = false;
  68947. if (errorCallback)
  68948. errorCallback();
  68949. };
  68950. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68951. // Your browser doesn't support IndexedDB
  68952. this.isSupported = false;
  68953. if (errorCallback)
  68954. errorCallback();
  68955. }
  68956. else {
  68957. // If the DB hasn't been opened or created yet
  68958. if (!this.db) {
  68959. this.hasReachedQuota = false;
  68960. this.isSupported = true;
  68961. var request = this.idbFactory.open("babylonjs", 1);
  68962. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68963. request.onerror = function (event) {
  68964. handleError();
  68965. };
  68966. // executes when a version change transaction cannot complete due to other active transactions
  68967. request.onblocked = function (event) {
  68968. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68969. handleError();
  68970. };
  68971. // DB has been opened successfully
  68972. request.onsuccess = function (event) {
  68973. _this.db = request.result;
  68974. successCallback();
  68975. };
  68976. // Initialization of the DB. Creating Scenes & Textures stores
  68977. request.onupgradeneeded = function (event) {
  68978. _this.db = (event.target).result;
  68979. if (_this.db) {
  68980. try {
  68981. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68982. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68983. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68984. }
  68985. catch (ex) {
  68986. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68987. handleError();
  68988. }
  68989. }
  68990. };
  68991. }
  68992. // DB has already been created and opened
  68993. else {
  68994. if (successCallback)
  68995. successCallback();
  68996. }
  68997. }
  68998. };
  68999. /**
  69000. * Loads an image from the database
  69001. * @param url defines the url to load from
  69002. * @param image defines the target DOM image
  69003. */
  69004. Database.prototype.loadImageFromDB = function (url, image) {
  69005. var _this = this;
  69006. var completeURL = Database._ReturnFullUrlLocation(url);
  69007. var saveAndLoadImage = function () {
  69008. if (!_this.hasReachedQuota && _this.db !== null) {
  69009. // the texture is not yet in the DB, let's try to save it
  69010. _this._saveImageIntoDBAsync(completeURL, image);
  69011. }
  69012. // If the texture is not in the DB and we've reached the DB quota limit
  69013. // let's load it directly from the web
  69014. else {
  69015. image.src = url;
  69016. }
  69017. };
  69018. if (!this.mustUpdateRessources) {
  69019. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69020. }
  69021. // First time we're download the images or update requested in the manifest file by a version change
  69022. else {
  69023. saveAndLoadImage();
  69024. }
  69025. };
  69026. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69027. if (this.isSupported && this.db !== null) {
  69028. var texture;
  69029. var transaction = this.db.transaction(["textures"]);
  69030. transaction.onabort = function (event) {
  69031. image.src = url;
  69032. };
  69033. transaction.oncomplete = function (event) {
  69034. var blobTextureURL;
  69035. if (texture) {
  69036. var URL = window.URL || window.webkitURL;
  69037. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69038. image.onerror = function () {
  69039. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69040. image.src = url;
  69041. };
  69042. image.src = blobTextureURL;
  69043. }
  69044. else {
  69045. notInDBCallback();
  69046. }
  69047. };
  69048. var getRequest = transaction.objectStore("textures").get(url);
  69049. getRequest.onsuccess = function (event) {
  69050. texture = (event.target).result;
  69051. };
  69052. getRequest.onerror = function (event) {
  69053. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69054. image.src = url;
  69055. };
  69056. }
  69057. else {
  69058. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69059. image.src = url;
  69060. }
  69061. };
  69062. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69063. var _this = this;
  69064. if (this.isSupported) {
  69065. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69066. var generateBlobUrl = function () {
  69067. var blobTextureURL;
  69068. if (blob) {
  69069. var URL = window.URL || window.webkitURL;
  69070. try {
  69071. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69072. }
  69073. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69074. catch (ex) {
  69075. blobTextureURL = URL.createObjectURL(blob);
  69076. }
  69077. }
  69078. if (blobTextureURL) {
  69079. image.src = blobTextureURL;
  69080. }
  69081. };
  69082. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69083. var xhr = new XMLHttpRequest(), blob;
  69084. xhr.open("GET", url, true);
  69085. xhr.responseType = "blob";
  69086. xhr.addEventListener("load", function () {
  69087. if (xhr.status === 200 && _this.db) {
  69088. // Blob as response (XHR2)
  69089. blob = xhr.response;
  69090. var transaction = _this.db.transaction(["textures"], "readwrite");
  69091. // the transaction could abort because of a QuotaExceededError error
  69092. transaction.onabort = function (event) {
  69093. try {
  69094. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69095. var srcElement = (event.srcElement || event.target);
  69096. var error = srcElement.error;
  69097. if (error && error.name === "QuotaExceededError") {
  69098. _this.hasReachedQuota = true;
  69099. }
  69100. }
  69101. catch (ex) { }
  69102. generateBlobUrl();
  69103. };
  69104. transaction.oncomplete = function (event) {
  69105. generateBlobUrl();
  69106. };
  69107. var newTexture = { textureUrl: url, data: blob };
  69108. try {
  69109. // Put the blob into the dabase
  69110. var addRequest = transaction.objectStore("textures").put(newTexture);
  69111. addRequest.onsuccess = function (event) {
  69112. };
  69113. addRequest.onerror = function (event) {
  69114. generateBlobUrl();
  69115. };
  69116. }
  69117. catch (ex) {
  69118. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69119. if (ex.code === 25) {
  69120. Database.IsUASupportingBlobStorage = false;
  69121. }
  69122. image.src = url;
  69123. }
  69124. }
  69125. else {
  69126. image.src = url;
  69127. }
  69128. }, false);
  69129. xhr.addEventListener("error", function (event) {
  69130. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69131. image.src = url;
  69132. }, false);
  69133. xhr.send();
  69134. }
  69135. else {
  69136. image.src = url;
  69137. }
  69138. }
  69139. else {
  69140. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69141. image.src = url;
  69142. }
  69143. };
  69144. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69145. var _this = this;
  69146. var updateVersion = function () {
  69147. // the version is not yet in the DB or we need to update it
  69148. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69149. };
  69150. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69151. };
  69152. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69153. var _this = this;
  69154. if (this.isSupported && this.db) {
  69155. var version;
  69156. try {
  69157. var transaction = this.db.transaction(["versions"]);
  69158. transaction.oncomplete = function (event) {
  69159. if (version) {
  69160. // If the version in the JSON file is different from the version in DB
  69161. if (_this.manifestVersionFound !== version.data) {
  69162. _this.mustUpdateRessources = true;
  69163. updateInDBCallback();
  69164. }
  69165. else {
  69166. callback(version.data);
  69167. }
  69168. }
  69169. // version was not found in DB
  69170. else {
  69171. _this.mustUpdateRessources = true;
  69172. updateInDBCallback();
  69173. }
  69174. };
  69175. transaction.onabort = function (event) {
  69176. callback(-1);
  69177. };
  69178. var getRequest = transaction.objectStore("versions").get(url);
  69179. getRequest.onsuccess = function (event) {
  69180. version = (event.target).result;
  69181. };
  69182. getRequest.onerror = function (event) {
  69183. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69184. callback(-1);
  69185. };
  69186. }
  69187. catch (ex) {
  69188. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69189. callback(-1);
  69190. }
  69191. }
  69192. else {
  69193. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69194. callback(-1);
  69195. }
  69196. };
  69197. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69198. var _this = this;
  69199. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69200. try {
  69201. // Open a transaction to the database
  69202. var transaction = this.db.transaction(["versions"], "readwrite");
  69203. // the transaction could abort because of a QuotaExceededError error
  69204. transaction.onabort = function (event) {
  69205. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69206. var error = event.srcElement['error'];
  69207. if (error && error.name === "QuotaExceededError") {
  69208. _this.hasReachedQuota = true;
  69209. }
  69210. }
  69211. catch (ex) { }
  69212. callback(-1);
  69213. };
  69214. transaction.oncomplete = function (event) {
  69215. callback(_this.manifestVersionFound);
  69216. };
  69217. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69218. // Put the scene into the database
  69219. var addRequest = transaction.objectStore("versions").put(newVersion);
  69220. addRequest.onsuccess = function (event) {
  69221. };
  69222. addRequest.onerror = function (event) {
  69223. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69224. };
  69225. }
  69226. catch (ex) {
  69227. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69228. callback(-1);
  69229. }
  69230. }
  69231. else {
  69232. callback(-1);
  69233. }
  69234. };
  69235. /**
  69236. * Loads a file from database
  69237. * @param url defines the URL to load from
  69238. * @param sceneLoaded defines a callback to call on success
  69239. * @param progressCallBack defines a callback to call when progress changed
  69240. * @param errorCallback defines a callback to call on error
  69241. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69242. */
  69243. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69244. var _this = this;
  69245. var completeUrl = Database._ReturnFullUrlLocation(url);
  69246. var saveAndLoadFile = function () {
  69247. // the scene is not yet in the DB, let's try to save it
  69248. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69249. };
  69250. this._checkVersionFromDB(completeUrl, function (version) {
  69251. if (version !== -1) {
  69252. if (!_this.mustUpdateRessources) {
  69253. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69254. }
  69255. else {
  69256. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69257. }
  69258. }
  69259. else {
  69260. if (errorCallback) {
  69261. errorCallback();
  69262. }
  69263. }
  69264. });
  69265. };
  69266. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69267. if (this.isSupported && this.db) {
  69268. var targetStore;
  69269. if (url.indexOf(".babylon") !== -1) {
  69270. targetStore = "scenes";
  69271. }
  69272. else {
  69273. targetStore = "textures";
  69274. }
  69275. var file;
  69276. var transaction = this.db.transaction([targetStore]);
  69277. transaction.oncomplete = function (event) {
  69278. if (file) {
  69279. callback(file.data);
  69280. }
  69281. // file was not found in DB
  69282. else {
  69283. notInDBCallback();
  69284. }
  69285. };
  69286. transaction.onabort = function (event) {
  69287. notInDBCallback();
  69288. };
  69289. var getRequest = transaction.objectStore(targetStore).get(url);
  69290. getRequest.onsuccess = function (event) {
  69291. file = (event.target).result;
  69292. };
  69293. getRequest.onerror = function (event) {
  69294. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69295. notInDBCallback();
  69296. };
  69297. }
  69298. else {
  69299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69300. callback();
  69301. }
  69302. };
  69303. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69304. var _this = this;
  69305. if (this.isSupported) {
  69306. var targetStore;
  69307. if (url.indexOf(".babylon") !== -1) {
  69308. targetStore = "scenes";
  69309. }
  69310. else {
  69311. targetStore = "textures";
  69312. }
  69313. // Create XHR
  69314. var xhr = new XMLHttpRequest();
  69315. var fileData;
  69316. xhr.open("GET", url, true);
  69317. if (useArrayBuffer) {
  69318. xhr.responseType = "arraybuffer";
  69319. }
  69320. if (progressCallback) {
  69321. xhr.onprogress = progressCallback;
  69322. }
  69323. xhr.addEventListener("load", function () {
  69324. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69325. // Blob as response (XHR2)
  69326. //fileData = xhr.responseText;
  69327. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69328. if (!_this.hasReachedQuota && _this.db) {
  69329. // Open a transaction to the database
  69330. var transaction = _this.db.transaction([targetStore], "readwrite");
  69331. // the transaction could abort because of a QuotaExceededError error
  69332. transaction.onabort = function (event) {
  69333. try {
  69334. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69335. var error = event.srcElement['error'];
  69336. if (error && error.name === "QuotaExceededError") {
  69337. _this.hasReachedQuota = true;
  69338. }
  69339. }
  69340. catch (ex) { }
  69341. callback(fileData);
  69342. };
  69343. transaction.oncomplete = function (event) {
  69344. callback(fileData);
  69345. };
  69346. var newFile;
  69347. if (targetStore === "scenes") {
  69348. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69349. }
  69350. else {
  69351. newFile = { textureUrl: url, data: fileData };
  69352. }
  69353. try {
  69354. // Put the scene into the database
  69355. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69356. addRequest.onsuccess = function (event) {
  69357. };
  69358. addRequest.onerror = function (event) {
  69359. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69360. };
  69361. }
  69362. catch (ex) {
  69363. callback(fileData);
  69364. }
  69365. }
  69366. else {
  69367. callback(fileData);
  69368. }
  69369. }
  69370. else {
  69371. callback();
  69372. }
  69373. }, false);
  69374. xhr.addEventListener("error", function (event) {
  69375. BABYLON.Tools.Error("error on XHR request.");
  69376. callback();
  69377. }, false);
  69378. xhr.send();
  69379. }
  69380. else {
  69381. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69382. callback();
  69383. }
  69384. };
  69385. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69386. Database.IsUASupportingBlobStorage = true;
  69387. /** Gets a boolean indicating if Database storate is enabled */
  69388. Database.IDBStorageEnabled = true;
  69389. Database._ParseURL = function (url) {
  69390. var a = document.createElement('a');
  69391. a.href = url;
  69392. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69393. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69394. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69395. return absLocation;
  69396. };
  69397. Database._ReturnFullUrlLocation = function (url) {
  69398. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69399. return (Database._ParseURL(window.location.href) + url);
  69400. }
  69401. else {
  69402. return url;
  69403. }
  69404. };
  69405. return Database;
  69406. }());
  69407. BABYLON.Database = Database;
  69408. })(BABYLON || (BABYLON = {}));
  69409. //# sourceMappingURL=babylon.database.js.map
  69410. var BABYLON;
  69411. (function (BABYLON) {
  69412. var FresnelParameters = /** @class */ (function () {
  69413. function FresnelParameters() {
  69414. this._isEnabled = true;
  69415. this.leftColor = BABYLON.Color3.White();
  69416. this.rightColor = BABYLON.Color3.Black();
  69417. this.bias = 0;
  69418. this.power = 1;
  69419. }
  69420. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69421. get: function () {
  69422. return this._isEnabled;
  69423. },
  69424. set: function (value) {
  69425. if (this._isEnabled === value) {
  69426. return;
  69427. }
  69428. this._isEnabled = value;
  69429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. FresnelParameters.prototype.clone = function () {
  69435. var newFresnelParameters = new FresnelParameters();
  69436. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69437. return newFresnelParameters;
  69438. };
  69439. FresnelParameters.prototype.serialize = function () {
  69440. var serializationObject = {};
  69441. serializationObject.isEnabled = this.isEnabled;
  69442. serializationObject.leftColor = this.leftColor.asArray();
  69443. serializationObject.rightColor = this.rightColor.asArray();
  69444. serializationObject.bias = this.bias;
  69445. serializationObject.power = this.power;
  69446. return serializationObject;
  69447. };
  69448. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69449. var fresnelParameters = new FresnelParameters();
  69450. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69451. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69452. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69453. fresnelParameters.bias = parsedFresnelParameters.bias;
  69454. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69455. return fresnelParameters;
  69456. };
  69457. return FresnelParameters;
  69458. }());
  69459. BABYLON.FresnelParameters = FresnelParameters;
  69460. })(BABYLON || (BABYLON = {}));
  69461. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69462. var BABYLON;
  69463. (function (BABYLON) {
  69464. var MultiMaterial = /** @class */ (function (_super) {
  69465. __extends(MultiMaterial, _super);
  69466. function MultiMaterial(name, scene) {
  69467. var _this = _super.call(this, name, scene, true) || this;
  69468. scene.multiMaterials.push(_this);
  69469. _this.subMaterials = new Array();
  69470. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69471. return _this;
  69472. }
  69473. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69474. get: function () {
  69475. return this._subMaterials;
  69476. },
  69477. set: function (value) {
  69478. this._subMaterials = value;
  69479. this._hookArray(value);
  69480. },
  69481. enumerable: true,
  69482. configurable: true
  69483. });
  69484. MultiMaterial.prototype._hookArray = function (array) {
  69485. var _this = this;
  69486. var oldPush = array.push;
  69487. array.push = function () {
  69488. var items = [];
  69489. for (var _i = 0; _i < arguments.length; _i++) {
  69490. items[_i] = arguments[_i];
  69491. }
  69492. var result = oldPush.apply(array, items);
  69493. _this._markAllSubMeshesAsTexturesDirty();
  69494. return result;
  69495. };
  69496. var oldSplice = array.splice;
  69497. array.splice = function (index, deleteCount) {
  69498. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69499. _this._markAllSubMeshesAsTexturesDirty();
  69500. return deleted;
  69501. };
  69502. };
  69503. // Properties
  69504. MultiMaterial.prototype.getSubMaterial = function (index) {
  69505. if (index < 0 || index >= this.subMaterials.length) {
  69506. return this.getScene().defaultMaterial;
  69507. }
  69508. return this.subMaterials[index];
  69509. };
  69510. MultiMaterial.prototype.getActiveTextures = function () {
  69511. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69512. if (subMaterial) {
  69513. return subMaterial.getActiveTextures();
  69514. }
  69515. else {
  69516. return [];
  69517. }
  69518. }));
  69519. var _a;
  69520. };
  69521. // Methods
  69522. MultiMaterial.prototype.getClassName = function () {
  69523. return "MultiMaterial";
  69524. };
  69525. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69526. for (var index = 0; index < this.subMaterials.length; index++) {
  69527. var subMaterial = this.subMaterials[index];
  69528. if (subMaterial) {
  69529. if (subMaterial.storeEffectOnSubMeshes) {
  69530. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69531. return false;
  69532. }
  69533. continue;
  69534. }
  69535. if (!subMaterial.isReady(mesh)) {
  69536. return false;
  69537. }
  69538. }
  69539. }
  69540. return true;
  69541. };
  69542. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69543. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69544. for (var index = 0; index < this.subMaterials.length; index++) {
  69545. var subMaterial = null;
  69546. var current = this.subMaterials[index];
  69547. if (cloneChildren && current) {
  69548. subMaterial = current.clone(name + "-" + current.name);
  69549. }
  69550. else {
  69551. subMaterial = this.subMaterials[index];
  69552. }
  69553. newMultiMaterial.subMaterials.push(subMaterial);
  69554. }
  69555. return newMultiMaterial;
  69556. };
  69557. MultiMaterial.prototype.serialize = function () {
  69558. var serializationObject = {};
  69559. serializationObject.name = this.name;
  69560. serializationObject.id = this.id;
  69561. if (BABYLON.Tags) {
  69562. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69563. }
  69564. serializationObject.materials = [];
  69565. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69566. var subMat = this.subMaterials[matIndex];
  69567. if (subMat) {
  69568. serializationObject.materials.push(subMat.id);
  69569. }
  69570. else {
  69571. serializationObject.materials.push(null);
  69572. }
  69573. }
  69574. return serializationObject;
  69575. };
  69576. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69577. var scene = this.getScene();
  69578. if (!scene) {
  69579. return;
  69580. }
  69581. var index = scene.multiMaterials.indexOf(this);
  69582. if (index >= 0) {
  69583. scene.multiMaterials.splice(index, 1);
  69584. }
  69585. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69586. };
  69587. return MultiMaterial;
  69588. }(BABYLON.Material));
  69589. BABYLON.MultiMaterial = MultiMaterial;
  69590. })(BABYLON || (BABYLON = {}));
  69591. //# sourceMappingURL=babylon.multiMaterial.js.map
  69592. var BABYLON;
  69593. (function (BABYLON) {
  69594. var FreeCameraTouchInput = /** @class */ (function () {
  69595. function FreeCameraTouchInput() {
  69596. this._offsetX = null;
  69597. this._offsetY = null;
  69598. this._pointerPressed = new Array();
  69599. this.touchAngularSensibility = 200000.0;
  69600. this.touchMoveSensibility = 250.0;
  69601. }
  69602. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69603. var _this = this;
  69604. var previousPosition = null;
  69605. if (this._pointerInput === undefined) {
  69606. this._onLostFocus = function (evt) {
  69607. _this._offsetX = null;
  69608. _this._offsetY = null;
  69609. };
  69610. this._pointerInput = function (p, s) {
  69611. var evt = p.event;
  69612. if (evt.pointerType === "mouse") {
  69613. return;
  69614. }
  69615. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69616. if (!noPreventDefault) {
  69617. evt.preventDefault();
  69618. }
  69619. _this._pointerPressed.push(evt.pointerId);
  69620. if (_this._pointerPressed.length !== 1) {
  69621. return;
  69622. }
  69623. previousPosition = {
  69624. x: evt.clientX,
  69625. y: evt.clientY
  69626. };
  69627. }
  69628. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69629. if (!noPreventDefault) {
  69630. evt.preventDefault();
  69631. }
  69632. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69633. if (index === -1) {
  69634. return;
  69635. }
  69636. _this._pointerPressed.splice(index, 1);
  69637. if (index != 0) {
  69638. return;
  69639. }
  69640. previousPosition = null;
  69641. _this._offsetX = null;
  69642. _this._offsetY = null;
  69643. }
  69644. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69645. if (!noPreventDefault) {
  69646. evt.preventDefault();
  69647. }
  69648. if (!previousPosition) {
  69649. return;
  69650. }
  69651. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69652. if (index != 0) {
  69653. return;
  69654. }
  69655. _this._offsetX = evt.clientX - previousPosition.x;
  69656. _this._offsetY = -(evt.clientY - previousPosition.y);
  69657. }
  69658. };
  69659. }
  69660. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69661. if (this._onLostFocus) {
  69662. element.addEventListener("blur", this._onLostFocus);
  69663. }
  69664. };
  69665. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69666. if (this._pointerInput && element) {
  69667. if (this._observer) {
  69668. this.camera.getScene().onPointerObservable.remove(this._observer);
  69669. this._observer = null;
  69670. }
  69671. if (this._onLostFocus) {
  69672. element.removeEventListener("blur", this._onLostFocus);
  69673. this._onLostFocus = null;
  69674. }
  69675. this._pointerPressed = [];
  69676. this._offsetX = null;
  69677. this._offsetY = null;
  69678. }
  69679. };
  69680. FreeCameraTouchInput.prototype.checkInputs = function () {
  69681. if (this._offsetX && this._offsetY) {
  69682. var camera = this.camera;
  69683. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69684. if (this._pointerPressed.length > 1) {
  69685. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69686. }
  69687. else {
  69688. var speed = camera._computeLocalCameraSpeed();
  69689. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69690. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69691. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69692. }
  69693. }
  69694. };
  69695. FreeCameraTouchInput.prototype.getClassName = function () {
  69696. return "FreeCameraTouchInput";
  69697. };
  69698. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69699. return "touch";
  69700. };
  69701. __decorate([
  69702. BABYLON.serialize()
  69703. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69704. __decorate([
  69705. BABYLON.serialize()
  69706. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69707. return FreeCameraTouchInput;
  69708. }());
  69709. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69710. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69711. })(BABYLON || (BABYLON = {}));
  69712. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69713. var BABYLON;
  69714. (function (BABYLON) {
  69715. // We're mainly based on the logic defined into the FreeCamera code
  69716. var TouchCamera = /** @class */ (function (_super) {
  69717. __extends(TouchCamera, _super);
  69718. //-- end properties for backward compatibility for inputs
  69719. function TouchCamera(name, position, scene) {
  69720. var _this = _super.call(this, name, position, scene) || this;
  69721. _this.inputs.addTouch();
  69722. _this._setupInputs();
  69723. return _this;
  69724. }
  69725. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69726. //-- Begin properties for backward compatibility for inputs
  69727. get: function () {
  69728. var touch = this.inputs.attached["touch"];
  69729. if (touch)
  69730. return touch.touchAngularSensibility;
  69731. return 0;
  69732. },
  69733. set: function (value) {
  69734. var touch = this.inputs.attached["touch"];
  69735. if (touch)
  69736. touch.touchAngularSensibility = value;
  69737. },
  69738. enumerable: true,
  69739. configurable: true
  69740. });
  69741. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69742. get: function () {
  69743. var touch = this.inputs.attached["touch"];
  69744. if (touch)
  69745. return touch.touchMoveSensibility;
  69746. return 0;
  69747. },
  69748. set: function (value) {
  69749. var touch = this.inputs.attached["touch"];
  69750. if (touch)
  69751. touch.touchMoveSensibility = value;
  69752. },
  69753. enumerable: true,
  69754. configurable: true
  69755. });
  69756. TouchCamera.prototype.getClassName = function () {
  69757. return "TouchCamera";
  69758. };
  69759. TouchCamera.prototype._setupInputs = function () {
  69760. var mouse = this.inputs.attached["mouse"];
  69761. if (mouse) {
  69762. mouse.touchEnabled = false;
  69763. }
  69764. };
  69765. return TouchCamera;
  69766. }(BABYLON.FreeCamera));
  69767. BABYLON.TouchCamera = TouchCamera;
  69768. })(BABYLON || (BABYLON = {}));
  69769. //# sourceMappingURL=babylon.touchCamera.js.map
  69770. var BABYLON;
  69771. (function (BABYLON) {
  69772. var ProceduralTexture = /** @class */ (function (_super) {
  69773. __extends(ProceduralTexture, _super);
  69774. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69775. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69777. if (isCube === void 0) { isCube = false; }
  69778. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69779. _this.isCube = isCube;
  69780. _this.isEnabled = true;
  69781. _this._currentRefreshId = -1;
  69782. _this._refreshRate = 1;
  69783. _this._vertexBuffers = {};
  69784. _this._uniforms = new Array();
  69785. _this._samplers = new Array();
  69786. _this._textures = {};
  69787. _this._floats = {};
  69788. _this._floatsArrays = {};
  69789. _this._colors3 = {};
  69790. _this._colors4 = {};
  69791. _this._vectors2 = {};
  69792. _this._vectors3 = {};
  69793. _this._matrices = {};
  69794. _this._fallbackTextureUsed = false;
  69795. scene.proceduralTextures.push(_this);
  69796. _this._engine = scene.getEngine();
  69797. _this.name = name;
  69798. _this.isRenderTarget = true;
  69799. _this._size = size;
  69800. _this._generateMipMaps = generateMipMaps;
  69801. _this.setFragment(fragment);
  69802. _this._fallbackTexture = fallbackTexture;
  69803. if (isCube) {
  69804. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69805. _this.setFloat("face", 0);
  69806. }
  69807. else {
  69808. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69809. }
  69810. // VBO
  69811. var vertices = [];
  69812. vertices.push(1, 1);
  69813. vertices.push(-1, 1);
  69814. vertices.push(-1, -1);
  69815. vertices.push(1, -1);
  69816. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69817. _this._createIndexBuffer();
  69818. return _this;
  69819. }
  69820. ProceduralTexture.prototype._createIndexBuffer = function () {
  69821. var engine = this._engine;
  69822. // Indices
  69823. var indices = [];
  69824. indices.push(0);
  69825. indices.push(1);
  69826. indices.push(2);
  69827. indices.push(0);
  69828. indices.push(2);
  69829. indices.push(3);
  69830. this._indexBuffer = engine.createIndexBuffer(indices);
  69831. };
  69832. ProceduralTexture.prototype._rebuild = function () {
  69833. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69834. if (vb) {
  69835. vb._rebuild();
  69836. }
  69837. this._createIndexBuffer();
  69838. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69839. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69840. }
  69841. };
  69842. ProceduralTexture.prototype.reset = function () {
  69843. if (this._effect === undefined) {
  69844. return;
  69845. }
  69846. var engine = this._engine;
  69847. engine._releaseEffect(this._effect);
  69848. };
  69849. ProceduralTexture.prototype.isReady = function () {
  69850. var _this = this;
  69851. var engine = this._engine;
  69852. var shaders;
  69853. if (!this._fragment) {
  69854. return false;
  69855. }
  69856. if (this._fallbackTextureUsed) {
  69857. return true;
  69858. }
  69859. if (this._fragment.fragmentElement !== undefined) {
  69860. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69861. }
  69862. else {
  69863. shaders = { vertex: "procedural", fragment: this._fragment };
  69864. }
  69865. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69866. _this.releaseInternalTexture();
  69867. if (_this._fallbackTexture) {
  69868. _this._texture = _this._fallbackTexture._texture;
  69869. if (_this._texture) {
  69870. _this._texture.incrementReferences();
  69871. }
  69872. }
  69873. _this._fallbackTextureUsed = true;
  69874. });
  69875. return this._effect.isReady();
  69876. };
  69877. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69878. this._currentRefreshId = -1;
  69879. };
  69880. ProceduralTexture.prototype.setFragment = function (fragment) {
  69881. this._fragment = fragment;
  69882. };
  69883. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69884. get: function () {
  69885. return this._refreshRate;
  69886. },
  69887. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69888. set: function (value) {
  69889. this._refreshRate = value;
  69890. this.resetRefreshCounter();
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. ProceduralTexture.prototype._shouldRender = function () {
  69896. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69897. return false;
  69898. }
  69899. if (this._fallbackTextureUsed) {
  69900. return false;
  69901. }
  69902. if (this._currentRefreshId === -1) { // At least render once
  69903. this._currentRefreshId = 1;
  69904. return true;
  69905. }
  69906. if (this.refreshRate === this._currentRefreshId) {
  69907. this._currentRefreshId = 1;
  69908. return true;
  69909. }
  69910. this._currentRefreshId++;
  69911. return false;
  69912. };
  69913. ProceduralTexture.prototype.getRenderSize = function () {
  69914. return this._size;
  69915. };
  69916. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69917. if (this._fallbackTextureUsed) {
  69918. return;
  69919. }
  69920. this.releaseInternalTexture();
  69921. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69922. };
  69923. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69924. if (this._uniforms.indexOf(uniformName) === -1) {
  69925. this._uniforms.push(uniformName);
  69926. }
  69927. };
  69928. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69929. if (this._samplers.indexOf(name) === -1) {
  69930. this._samplers.push(name);
  69931. }
  69932. this._textures[name] = texture;
  69933. return this;
  69934. };
  69935. ProceduralTexture.prototype.setFloat = function (name, value) {
  69936. this._checkUniform(name);
  69937. this._floats[name] = value;
  69938. return this;
  69939. };
  69940. ProceduralTexture.prototype.setFloats = function (name, value) {
  69941. this._checkUniform(name);
  69942. this._floatsArrays[name] = value;
  69943. return this;
  69944. };
  69945. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69946. this._checkUniform(name);
  69947. this._colors3[name] = value;
  69948. return this;
  69949. };
  69950. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69951. this._checkUniform(name);
  69952. this._colors4[name] = value;
  69953. return this;
  69954. };
  69955. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69956. this._checkUniform(name);
  69957. this._vectors2[name] = value;
  69958. return this;
  69959. };
  69960. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69961. this._checkUniform(name);
  69962. this._vectors3[name] = value;
  69963. return this;
  69964. };
  69965. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69966. this._checkUniform(name);
  69967. this._matrices[name] = value;
  69968. return this;
  69969. };
  69970. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69971. var scene = this.getScene();
  69972. if (!scene) {
  69973. return;
  69974. }
  69975. var engine = this._engine;
  69976. // Render
  69977. engine.enableEffect(this._effect);
  69978. engine.setState(false);
  69979. // Texture
  69980. for (var name in this._textures) {
  69981. this._effect.setTexture(name, this._textures[name]);
  69982. }
  69983. // Float
  69984. for (name in this._floats) {
  69985. this._effect.setFloat(name, this._floats[name]);
  69986. }
  69987. // Floats
  69988. for (name in this._floatsArrays) {
  69989. this._effect.setArray(name, this._floatsArrays[name]);
  69990. }
  69991. // Color3
  69992. for (name in this._colors3) {
  69993. this._effect.setColor3(name, this._colors3[name]);
  69994. }
  69995. // Color4
  69996. for (name in this._colors4) {
  69997. var color = this._colors4[name];
  69998. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69999. }
  70000. // Vector2
  70001. for (name in this._vectors2) {
  70002. this._effect.setVector2(name, this._vectors2[name]);
  70003. }
  70004. // Vector3
  70005. for (name in this._vectors3) {
  70006. this._effect.setVector3(name, this._vectors3[name]);
  70007. }
  70008. // Matrix
  70009. for (name in this._matrices) {
  70010. this._effect.setMatrix(name, this._matrices[name]);
  70011. }
  70012. if (!this._texture) {
  70013. return;
  70014. }
  70015. if (this.isCube) {
  70016. for (var face = 0; face < 6; face++) {
  70017. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70018. // VBOs
  70019. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70020. this._effect.setFloat("face", face);
  70021. // Clear
  70022. engine.clear(scene.clearColor, true, true, true);
  70023. // Draw order
  70024. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70025. // Mipmaps
  70026. if (face === 5) {
  70027. engine.generateMipMapsForCubemap(this._texture);
  70028. }
  70029. }
  70030. }
  70031. else {
  70032. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70033. // VBOs
  70034. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70035. // Clear
  70036. engine.clear(scene.clearColor, true, true, true);
  70037. // Draw order
  70038. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70039. }
  70040. // Unbind
  70041. engine.unBindFramebuffer(this._texture, this.isCube);
  70042. if (this.onGenerated) {
  70043. this.onGenerated();
  70044. }
  70045. };
  70046. ProceduralTexture.prototype.clone = function () {
  70047. var textureSize = this.getSize();
  70048. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70049. // Base texture
  70050. newTexture.hasAlpha = this.hasAlpha;
  70051. newTexture.level = this.level;
  70052. // RenderTarget Texture
  70053. newTexture.coordinatesMode = this.coordinatesMode;
  70054. return newTexture;
  70055. };
  70056. ProceduralTexture.prototype.dispose = function () {
  70057. var scene = this.getScene();
  70058. if (!scene) {
  70059. return;
  70060. }
  70061. var index = scene.proceduralTextures.indexOf(this);
  70062. if (index >= 0) {
  70063. scene.proceduralTextures.splice(index, 1);
  70064. }
  70065. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70066. if (vertexBuffer) {
  70067. vertexBuffer.dispose();
  70068. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70069. }
  70070. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70071. this._indexBuffer = null;
  70072. }
  70073. _super.prototype.dispose.call(this);
  70074. };
  70075. return ProceduralTexture;
  70076. }(BABYLON.Texture));
  70077. BABYLON.ProceduralTexture = ProceduralTexture;
  70078. })(BABYLON || (BABYLON = {}));
  70079. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70080. var BABYLON;
  70081. (function (BABYLON) {
  70082. var CustomProceduralTexture = /** @class */ (function (_super) {
  70083. __extends(CustomProceduralTexture, _super);
  70084. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70085. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70086. _this._animate = true;
  70087. _this._time = 0;
  70088. _this._texturePath = texturePath;
  70089. //Try to load json
  70090. _this.loadJson(texturePath);
  70091. _this.refreshRate = 1;
  70092. return _this;
  70093. }
  70094. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70095. var _this = this;
  70096. var noConfigFile = function () {
  70097. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70098. try {
  70099. _this.setFragment(_this._texturePath);
  70100. }
  70101. catch (ex) {
  70102. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70103. }
  70104. };
  70105. var configFileUrl = jsonUrl + "/config.json";
  70106. var xhr = new XMLHttpRequest();
  70107. xhr.open("GET", configFileUrl, true);
  70108. xhr.addEventListener("load", function () {
  70109. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70110. try {
  70111. _this._config = JSON.parse(xhr.response);
  70112. _this.updateShaderUniforms();
  70113. _this.updateTextures();
  70114. _this.setFragment(_this._texturePath + "/custom");
  70115. _this._animate = _this._config.animate;
  70116. _this.refreshRate = _this._config.refreshrate;
  70117. }
  70118. catch (ex) {
  70119. noConfigFile();
  70120. }
  70121. }
  70122. else {
  70123. noConfigFile();
  70124. }
  70125. }, false);
  70126. xhr.addEventListener("error", function () {
  70127. noConfigFile();
  70128. }, false);
  70129. try {
  70130. xhr.send();
  70131. }
  70132. catch (ex) {
  70133. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70134. }
  70135. };
  70136. CustomProceduralTexture.prototype.isReady = function () {
  70137. if (!_super.prototype.isReady.call(this)) {
  70138. return false;
  70139. }
  70140. for (var name in this._textures) {
  70141. var texture = this._textures[name];
  70142. if (!texture.isReady()) {
  70143. return false;
  70144. }
  70145. }
  70146. return true;
  70147. };
  70148. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70149. var scene = this.getScene();
  70150. if (this._animate && scene) {
  70151. this._time += scene.getAnimationRatio() * 0.03;
  70152. this.updateShaderUniforms();
  70153. }
  70154. _super.prototype.render.call(this, useCameraPostProcess);
  70155. };
  70156. CustomProceduralTexture.prototype.updateTextures = function () {
  70157. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70158. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70159. }
  70160. };
  70161. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70162. if (this._config) {
  70163. for (var j = 0; j < this._config.uniforms.length; j++) {
  70164. var uniform = this._config.uniforms[j];
  70165. switch (uniform.type) {
  70166. case "float":
  70167. this.setFloat(uniform.name, uniform.value);
  70168. break;
  70169. case "color3":
  70170. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70171. break;
  70172. case "color4":
  70173. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70174. break;
  70175. case "vector2":
  70176. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70177. break;
  70178. case "vector3":
  70179. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70180. break;
  70181. }
  70182. }
  70183. }
  70184. this.setFloat("time", this._time);
  70185. };
  70186. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70187. get: function () {
  70188. return this._animate;
  70189. },
  70190. set: function (value) {
  70191. this._animate = value;
  70192. },
  70193. enumerable: true,
  70194. configurable: true
  70195. });
  70196. return CustomProceduralTexture;
  70197. }(BABYLON.ProceduralTexture));
  70198. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70199. })(BABYLON || (BABYLON = {}));
  70200. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70201. var BABYLON;
  70202. (function (BABYLON) {
  70203. var FreeCameraGamepadInput = /** @class */ (function () {
  70204. function FreeCameraGamepadInput() {
  70205. this.gamepadAngularSensibility = 200;
  70206. this.gamepadMoveSensibility = 40;
  70207. // private members
  70208. this._cameraTransform = BABYLON.Matrix.Identity();
  70209. this._deltaTransform = BABYLON.Vector3.Zero();
  70210. this._vector3 = BABYLON.Vector3.Zero();
  70211. this._vector2 = BABYLON.Vector2.Zero();
  70212. }
  70213. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70214. var _this = this;
  70215. var manager = this.camera.getScene().gamepadManager;
  70216. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70217. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70218. // prioritize XBOX gamepads.
  70219. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70220. _this.gamepad = gamepad;
  70221. }
  70222. }
  70223. });
  70224. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70225. if (_this.gamepad === gamepad) {
  70226. _this.gamepad = null;
  70227. }
  70228. });
  70229. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70230. };
  70231. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70232. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70233. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70234. this.gamepad = null;
  70235. };
  70236. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70237. if (this.gamepad && this.gamepad.leftStick) {
  70238. var camera = this.camera;
  70239. var LSValues = this.gamepad.leftStick;
  70240. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70241. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70242. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70243. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70244. var RSValues = this.gamepad.rightStick;
  70245. if (RSValues) {
  70246. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70247. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70248. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70249. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70250. }
  70251. else {
  70252. RSValues = { x: 0, y: 0 };
  70253. }
  70254. if (!camera.rotationQuaternion) {
  70255. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70256. }
  70257. else {
  70258. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70259. }
  70260. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70261. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70262. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70263. camera.cameraDirection.addInPlace(this._deltaTransform);
  70264. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70265. camera.cameraRotation.addInPlace(this._vector2);
  70266. }
  70267. };
  70268. FreeCameraGamepadInput.prototype.getClassName = function () {
  70269. return "FreeCameraGamepadInput";
  70270. };
  70271. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70272. return "gamepad";
  70273. };
  70274. __decorate([
  70275. BABYLON.serialize()
  70276. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70277. __decorate([
  70278. BABYLON.serialize()
  70279. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70280. return FreeCameraGamepadInput;
  70281. }());
  70282. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70283. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70284. })(BABYLON || (BABYLON = {}));
  70285. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70286. var BABYLON;
  70287. (function (BABYLON) {
  70288. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70289. function ArcRotateCameraGamepadInput() {
  70290. this.gamepadRotationSensibility = 80;
  70291. this.gamepadMoveSensibility = 40;
  70292. }
  70293. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70294. var _this = this;
  70295. var manager = this.camera.getScene().gamepadManager;
  70296. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70297. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70298. // prioritize XBOX gamepads.
  70299. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70300. _this.gamepad = gamepad;
  70301. }
  70302. }
  70303. });
  70304. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70305. if (_this.gamepad === gamepad) {
  70306. _this.gamepad = null;
  70307. }
  70308. });
  70309. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70310. };
  70311. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70312. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70313. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70314. this.gamepad = null;
  70315. };
  70316. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70317. if (this.gamepad) {
  70318. var camera = this.camera;
  70319. var RSValues = this.gamepad.rightStick;
  70320. if (RSValues) {
  70321. if (RSValues.x != 0) {
  70322. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70323. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70324. camera.inertialAlphaOffset += normalizedRX;
  70325. }
  70326. }
  70327. if (RSValues.y != 0) {
  70328. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70329. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70330. camera.inertialBetaOffset += normalizedRY;
  70331. }
  70332. }
  70333. }
  70334. var LSValues = this.gamepad.leftStick;
  70335. if (LSValues && LSValues.y != 0) {
  70336. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70337. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70338. this.camera.inertialRadiusOffset -= normalizedLY;
  70339. }
  70340. }
  70341. }
  70342. };
  70343. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70344. return "ArcRotateCameraGamepadInput";
  70345. };
  70346. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70347. return "gamepad";
  70348. };
  70349. __decorate([
  70350. BABYLON.serialize()
  70351. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70352. __decorate([
  70353. BABYLON.serialize()
  70354. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70355. return ArcRotateCameraGamepadInput;
  70356. }());
  70357. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70358. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70359. })(BABYLON || (BABYLON = {}));
  70360. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70361. var BABYLON;
  70362. (function (BABYLON) {
  70363. var GamepadManager = /** @class */ (function () {
  70364. function GamepadManager(_scene) {
  70365. var _this = this;
  70366. this._scene = _scene;
  70367. this._babylonGamepads = [];
  70368. this._oneGamepadConnected = false;
  70369. this._isMonitoring = false;
  70370. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70371. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70372. this._gamepadEventSupported = false;
  70373. }
  70374. else {
  70375. this._gamepadEventSupported = 'GamepadEvent' in window;
  70376. this._gamepadSupport = (navigator.getGamepads ||
  70377. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70378. }
  70379. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70380. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70381. for (var i in _this._babylonGamepads) {
  70382. var gamepad = _this._babylonGamepads[i];
  70383. if (gamepad && gamepad._isConnected) {
  70384. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70385. }
  70386. }
  70387. });
  70388. this._onGamepadConnectedEvent = function (evt) {
  70389. var gamepad = evt.gamepad;
  70390. if (gamepad.index in _this._babylonGamepads) {
  70391. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70392. return;
  70393. }
  70394. }
  70395. var newGamepad;
  70396. if (_this._babylonGamepads[gamepad.index]) {
  70397. newGamepad = _this._babylonGamepads[gamepad.index];
  70398. newGamepad.browserGamepad = gamepad;
  70399. newGamepad._isConnected = true;
  70400. }
  70401. else {
  70402. newGamepad = _this._addNewGamepad(gamepad);
  70403. }
  70404. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70405. _this._startMonitoringGamepads();
  70406. };
  70407. this._onGamepadDisconnectedEvent = function (evt) {
  70408. var gamepad = evt.gamepad;
  70409. // Remove the gamepad from the list of gamepads to monitor.
  70410. for (var i in _this._babylonGamepads) {
  70411. if (_this._babylonGamepads[i].index === gamepad.index) {
  70412. var disconnectedGamepad = _this._babylonGamepads[i];
  70413. disconnectedGamepad._isConnected = false;
  70414. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70415. break;
  70416. }
  70417. }
  70418. };
  70419. if (this._gamepadSupport) {
  70420. //first add already-connected gamepads
  70421. this._updateGamepadObjects();
  70422. if (this._babylonGamepads.length) {
  70423. this._startMonitoringGamepads();
  70424. }
  70425. // Checking if the gamepad connected event is supported (like in Firefox)
  70426. if (this._gamepadEventSupported) {
  70427. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70428. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70429. }
  70430. else {
  70431. this._startMonitoringGamepads();
  70432. }
  70433. }
  70434. }
  70435. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70436. get: function () {
  70437. return this._babylonGamepads;
  70438. },
  70439. enumerable: true,
  70440. configurable: true
  70441. });
  70442. GamepadManager.prototype.getGamepadByType = function (type) {
  70443. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70444. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70445. var gamepad = _a[_i];
  70446. if (gamepad && gamepad.type === type) {
  70447. return gamepad;
  70448. }
  70449. }
  70450. return null;
  70451. };
  70452. GamepadManager.prototype.dispose = function () {
  70453. if (this._gamepadEventSupported) {
  70454. if (this._onGamepadConnectedEvent) {
  70455. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70456. }
  70457. if (this._onGamepadDisconnectedEvent) {
  70458. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70459. }
  70460. this._onGamepadConnectedEvent = null;
  70461. this._onGamepadDisconnectedEvent = null;
  70462. }
  70463. this._babylonGamepads.forEach(function (gamepad) {
  70464. gamepad.dispose();
  70465. });
  70466. this.onGamepadConnectedObservable.clear();
  70467. this.onGamepadDisconnectedObservable.clear();
  70468. this._oneGamepadConnected = false;
  70469. this._stopMonitoringGamepads();
  70470. this._babylonGamepads = [];
  70471. };
  70472. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70473. if (!this._oneGamepadConnected) {
  70474. this._oneGamepadConnected = true;
  70475. }
  70476. var newGamepad;
  70477. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70478. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70479. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70480. }
  70481. // if pose is supported, use the (WebVR) pose enabled controller
  70482. else if (gamepad.pose) {
  70483. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70484. }
  70485. else {
  70486. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70487. }
  70488. this._babylonGamepads[newGamepad.index] = newGamepad;
  70489. return newGamepad;
  70490. };
  70491. GamepadManager.prototype._startMonitoringGamepads = function () {
  70492. if (!this._isMonitoring) {
  70493. this._isMonitoring = true;
  70494. //back-comp
  70495. if (!this._scene) {
  70496. this._checkGamepadsStatus();
  70497. }
  70498. }
  70499. };
  70500. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70501. this._isMonitoring = false;
  70502. };
  70503. GamepadManager.prototype._checkGamepadsStatus = function () {
  70504. var _this = this;
  70505. // Hack to be compatible Chrome
  70506. this._updateGamepadObjects();
  70507. for (var i in this._babylonGamepads) {
  70508. var gamepad = this._babylonGamepads[i];
  70509. if (!gamepad || !gamepad.isConnected) {
  70510. continue;
  70511. }
  70512. gamepad.update();
  70513. }
  70514. if (this._isMonitoring && !this._scene) {
  70515. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70516. }
  70517. };
  70518. // This function is called only on Chrome, which does not properly support
  70519. // connection/disconnection events and forces you to recopy again the gamepad object
  70520. GamepadManager.prototype._updateGamepadObjects = function () {
  70521. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70522. for (var i = 0; i < gamepads.length; i++) {
  70523. var gamepad = gamepads[i];
  70524. if (gamepad) {
  70525. if (!this._babylonGamepads[gamepad.index]) {
  70526. var newGamepad = this._addNewGamepad(gamepad);
  70527. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70528. }
  70529. else {
  70530. // Forced to copy again this object for Chrome for unknown reason
  70531. this._babylonGamepads[i].browserGamepad = gamepad;
  70532. if (!this._babylonGamepads[i].isConnected) {
  70533. this._babylonGamepads[i]._isConnected = true;
  70534. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70535. }
  70536. }
  70537. }
  70538. }
  70539. };
  70540. return GamepadManager;
  70541. }());
  70542. BABYLON.GamepadManager = GamepadManager;
  70543. })(BABYLON || (BABYLON = {}));
  70544. //# sourceMappingURL=babylon.gamepadManager.js.map
  70545. var BABYLON;
  70546. (function (BABYLON) {
  70547. var StickValues = /** @class */ (function () {
  70548. function StickValues(x, y) {
  70549. this.x = x;
  70550. this.y = y;
  70551. }
  70552. return StickValues;
  70553. }());
  70554. BABYLON.StickValues = StickValues;
  70555. var Gamepad = /** @class */ (function () {
  70556. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70557. if (leftStickX === void 0) { leftStickX = 0; }
  70558. if (leftStickY === void 0) { leftStickY = 1; }
  70559. if (rightStickX === void 0) { rightStickX = 2; }
  70560. if (rightStickY === void 0) { rightStickY = 3; }
  70561. this.id = id;
  70562. this.index = index;
  70563. this.browserGamepad = browserGamepad;
  70564. this._isConnected = true;
  70565. this._invertLeftStickY = false;
  70566. this.type = Gamepad.GAMEPAD;
  70567. this._leftStickAxisX = leftStickX;
  70568. this._leftStickAxisY = leftStickY;
  70569. this._rightStickAxisX = rightStickX;
  70570. this._rightStickAxisY = rightStickY;
  70571. if (this.browserGamepad.axes.length >= 2) {
  70572. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70573. }
  70574. if (this.browserGamepad.axes.length >= 4) {
  70575. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70576. }
  70577. }
  70578. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70579. get: function () {
  70580. return this._isConnected;
  70581. },
  70582. enumerable: true,
  70583. configurable: true
  70584. });
  70585. Gamepad.prototype.onleftstickchanged = function (callback) {
  70586. this._onleftstickchanged = callback;
  70587. };
  70588. Gamepad.prototype.onrightstickchanged = function (callback) {
  70589. this._onrightstickchanged = callback;
  70590. };
  70591. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70592. get: function () {
  70593. return this._leftStick;
  70594. },
  70595. set: function (newValues) {
  70596. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70597. this._onleftstickchanged(newValues);
  70598. }
  70599. this._leftStick = newValues;
  70600. },
  70601. enumerable: true,
  70602. configurable: true
  70603. });
  70604. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70605. get: function () {
  70606. return this._rightStick;
  70607. },
  70608. set: function (newValues) {
  70609. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70610. this._onrightstickchanged(newValues);
  70611. }
  70612. this._rightStick = newValues;
  70613. },
  70614. enumerable: true,
  70615. configurable: true
  70616. });
  70617. Gamepad.prototype.update = function () {
  70618. if (this._leftStick) {
  70619. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70620. if (this._invertLeftStickY) {
  70621. this.leftStick.y *= -1;
  70622. }
  70623. }
  70624. if (this._rightStick) {
  70625. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70626. }
  70627. };
  70628. Gamepad.prototype.dispose = function () {
  70629. };
  70630. Gamepad.GAMEPAD = 0;
  70631. Gamepad.GENERIC = 1;
  70632. Gamepad.XBOX = 2;
  70633. Gamepad.POSE_ENABLED = 3;
  70634. return Gamepad;
  70635. }());
  70636. BABYLON.Gamepad = Gamepad;
  70637. var GenericPad = /** @class */ (function (_super) {
  70638. __extends(GenericPad, _super);
  70639. function GenericPad(id, index, browserGamepad) {
  70640. var _this = _super.call(this, id, index, browserGamepad) || this;
  70641. _this.onButtonDownObservable = new BABYLON.Observable();
  70642. _this.onButtonUpObservable = new BABYLON.Observable();
  70643. _this.type = Gamepad.GENERIC;
  70644. _this._buttons = new Array(browserGamepad.buttons.length);
  70645. return _this;
  70646. }
  70647. GenericPad.prototype.onbuttondown = function (callback) {
  70648. this._onbuttondown = callback;
  70649. };
  70650. GenericPad.prototype.onbuttonup = function (callback) {
  70651. this._onbuttonup = callback;
  70652. };
  70653. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70654. if (newValue !== currentValue) {
  70655. if (newValue === 1) {
  70656. if (this._onbuttondown) {
  70657. this._onbuttondown(buttonIndex);
  70658. }
  70659. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70660. }
  70661. if (newValue === 0) {
  70662. if (this._onbuttonup) {
  70663. this._onbuttonup(buttonIndex);
  70664. }
  70665. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70666. }
  70667. }
  70668. return newValue;
  70669. };
  70670. GenericPad.prototype.update = function () {
  70671. _super.prototype.update.call(this);
  70672. for (var index = 0; index < this._buttons.length; index++) {
  70673. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70674. }
  70675. };
  70676. GenericPad.prototype.dispose = function () {
  70677. _super.prototype.dispose.call(this);
  70678. this.onButtonDownObservable.clear();
  70679. this.onButtonUpObservable.clear();
  70680. };
  70681. return GenericPad;
  70682. }(Gamepad));
  70683. BABYLON.GenericPad = GenericPad;
  70684. })(BABYLON || (BABYLON = {}));
  70685. //# sourceMappingURL=babylon.gamepad.js.map
  70686. var BABYLON;
  70687. (function (BABYLON) {
  70688. /**
  70689. * Defines supported buttons for XBox360 compatible gamepads
  70690. */
  70691. var Xbox360Button;
  70692. (function (Xbox360Button) {
  70693. /** A */
  70694. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70695. /** B */
  70696. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70697. /** X */
  70698. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70699. /** Y */
  70700. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70701. /** Start */
  70702. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70703. /** Back */
  70704. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70705. /** Left button */
  70706. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70707. /** Right button */
  70708. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70709. /** Left stick */
  70710. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70711. /** Right stick */
  70712. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70713. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70714. /** Defines values for XBox360 DPad */
  70715. var Xbox360Dpad;
  70716. (function (Xbox360Dpad) {
  70717. /** Up */
  70718. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70719. /** Down */
  70720. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70721. /** Left */
  70722. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70723. /** Right */
  70724. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70725. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70726. /**
  70727. * Defines a XBox360 gamepad
  70728. */
  70729. var Xbox360Pad = /** @class */ (function (_super) {
  70730. __extends(Xbox360Pad, _super);
  70731. /**
  70732. * Creates a new XBox360 gamepad object
  70733. * @param id defines the id of this gamepad
  70734. * @param index defines its index
  70735. * @param gamepad defines the internal HTML gamepad object
  70736. * @param xboxOne defines if it is a XBox One gamepad
  70737. */
  70738. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70739. if (xboxOne === void 0) { xboxOne = false; }
  70740. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70741. _this._leftTrigger = 0;
  70742. _this._rightTrigger = 0;
  70743. /** Observable raised when a button is pressed */
  70744. _this.onButtonDownObservable = new BABYLON.Observable();
  70745. /** Observable raised when a button is released */
  70746. _this.onButtonUpObservable = new BABYLON.Observable();
  70747. /** Observable raised when a pad is pressed */
  70748. _this.onPadDownObservable = new BABYLON.Observable();
  70749. /** Observable raised when a pad is released */
  70750. _this.onPadUpObservable = new BABYLON.Observable();
  70751. _this._buttonA = 0;
  70752. _this._buttonB = 0;
  70753. _this._buttonX = 0;
  70754. _this._buttonY = 0;
  70755. _this._buttonBack = 0;
  70756. _this._buttonStart = 0;
  70757. _this._buttonLB = 0;
  70758. _this._buttonRB = 0;
  70759. _this._buttonLeftStick = 0;
  70760. _this._buttonRightStick = 0;
  70761. _this._dPadUp = 0;
  70762. _this._dPadDown = 0;
  70763. _this._dPadLeft = 0;
  70764. _this._dPadRight = 0;
  70765. _this._isXboxOnePad = false;
  70766. _this.type = BABYLON.Gamepad.XBOX;
  70767. _this._isXboxOnePad = xboxOne;
  70768. return _this;
  70769. }
  70770. /**
  70771. * Defines the callback to call when left trigger is pressed
  70772. * @param callback defines the callback to use
  70773. */
  70774. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70775. this._onlefttriggerchanged = callback;
  70776. };
  70777. /**
  70778. * Defines the callback to call when right trigger is pressed
  70779. * @param callback defines the callback to use
  70780. */
  70781. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70782. this._onrighttriggerchanged = callback;
  70783. };
  70784. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70785. /**
  70786. * Gets or sets left trigger value
  70787. */
  70788. get: function () {
  70789. return this._leftTrigger;
  70790. },
  70791. set: function (newValue) {
  70792. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70793. this._onlefttriggerchanged(newValue);
  70794. }
  70795. this._leftTrigger = newValue;
  70796. },
  70797. enumerable: true,
  70798. configurable: true
  70799. });
  70800. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70801. /**
  70802. * Gets or sets right trigger value
  70803. */
  70804. get: function () {
  70805. return this._rightTrigger;
  70806. },
  70807. set: function (newValue) {
  70808. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70809. this._onrighttriggerchanged(newValue);
  70810. }
  70811. this._rightTrigger = newValue;
  70812. },
  70813. enumerable: true,
  70814. configurable: true
  70815. });
  70816. /**
  70817. * Defines the callback to call when a button is pressed
  70818. * @param callback defines the callback to use
  70819. */
  70820. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70821. this._onbuttondown = callback;
  70822. };
  70823. /**
  70824. * Defines the callback to call when a button is released
  70825. * @param callback defines the callback to use
  70826. */
  70827. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70828. this._onbuttonup = callback;
  70829. };
  70830. /**
  70831. * Defines the callback to call when a pad is pressed
  70832. * @param callback defines the callback to use
  70833. */
  70834. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70835. this._ondpaddown = callback;
  70836. };
  70837. /**
  70838. * Defines the callback to call when a pad is released
  70839. * @param callback defines the callback to use
  70840. */
  70841. Xbox360Pad.prototype.ondpadup = function (callback) {
  70842. this._ondpadup = callback;
  70843. };
  70844. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70845. if (newValue !== currentValue) {
  70846. if (newValue === 1) {
  70847. if (this._onbuttondown) {
  70848. this._onbuttondown(buttonType);
  70849. }
  70850. this.onButtonDownObservable.notifyObservers(buttonType);
  70851. }
  70852. if (newValue === 0) {
  70853. if (this._onbuttonup) {
  70854. this._onbuttonup(buttonType);
  70855. }
  70856. this.onButtonUpObservable.notifyObservers(buttonType);
  70857. }
  70858. }
  70859. return newValue;
  70860. };
  70861. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70862. if (newValue !== currentValue) {
  70863. if (newValue === 1) {
  70864. if (this._ondpaddown) {
  70865. this._ondpaddown(buttonType);
  70866. }
  70867. this.onPadDownObservable.notifyObservers(buttonType);
  70868. }
  70869. if (newValue === 0) {
  70870. if (this._ondpadup) {
  70871. this._ondpadup(buttonType);
  70872. }
  70873. this.onPadUpObservable.notifyObservers(buttonType);
  70874. }
  70875. }
  70876. return newValue;
  70877. };
  70878. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70879. /** Gets or sets value of A button */
  70880. get: function () {
  70881. return this._buttonA;
  70882. },
  70883. set: function (value) {
  70884. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70885. },
  70886. enumerable: true,
  70887. configurable: true
  70888. });
  70889. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70890. /** Gets or sets value of B button */
  70891. get: function () {
  70892. return this._buttonB;
  70893. },
  70894. set: function (value) {
  70895. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70896. },
  70897. enumerable: true,
  70898. configurable: true
  70899. });
  70900. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70901. /** Gets or sets value of X button */
  70902. get: function () {
  70903. return this._buttonX;
  70904. },
  70905. set: function (value) {
  70906. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70907. },
  70908. enumerable: true,
  70909. configurable: true
  70910. });
  70911. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70912. /** Gets or sets value of Y button */
  70913. get: function () {
  70914. return this._buttonY;
  70915. },
  70916. set: function (value) {
  70917. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70918. },
  70919. enumerable: true,
  70920. configurable: true
  70921. });
  70922. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70923. /** Gets or sets value of Start button */
  70924. get: function () {
  70925. return this._buttonStart;
  70926. },
  70927. set: function (value) {
  70928. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70929. },
  70930. enumerable: true,
  70931. configurable: true
  70932. });
  70933. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70934. /** Gets or sets value of Back button */
  70935. get: function () {
  70936. return this._buttonBack;
  70937. },
  70938. set: function (value) {
  70939. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70940. },
  70941. enumerable: true,
  70942. configurable: true
  70943. });
  70944. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70945. /** Gets or sets value of Left button */
  70946. get: function () {
  70947. return this._buttonLB;
  70948. },
  70949. set: function (value) {
  70950. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70951. },
  70952. enumerable: true,
  70953. configurable: true
  70954. });
  70955. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70956. /** Gets or sets value of Right button */
  70957. get: function () {
  70958. return this._buttonRB;
  70959. },
  70960. set: function (value) {
  70961. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70962. },
  70963. enumerable: true,
  70964. configurable: true
  70965. });
  70966. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70967. /** Gets or sets value of left stick */
  70968. get: function () {
  70969. return this._buttonLeftStick;
  70970. },
  70971. set: function (value) {
  70972. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70973. },
  70974. enumerable: true,
  70975. configurable: true
  70976. });
  70977. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70978. /** Gets or sets value of right stick */
  70979. get: function () {
  70980. return this._buttonRightStick;
  70981. },
  70982. set: function (value) {
  70983. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70984. },
  70985. enumerable: true,
  70986. configurable: true
  70987. });
  70988. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70989. /** Gets or sets value of DPad up */
  70990. get: function () {
  70991. return this._dPadUp;
  70992. },
  70993. set: function (value) {
  70994. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70995. },
  70996. enumerable: true,
  70997. configurable: true
  70998. });
  70999. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71000. /** Gets or sets value of DPad down */
  71001. get: function () {
  71002. return this._dPadDown;
  71003. },
  71004. set: function (value) {
  71005. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71006. },
  71007. enumerable: true,
  71008. configurable: true
  71009. });
  71010. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71011. /** Gets or sets value of DPad left */
  71012. get: function () {
  71013. return this._dPadLeft;
  71014. },
  71015. set: function (value) {
  71016. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71017. },
  71018. enumerable: true,
  71019. configurable: true
  71020. });
  71021. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71022. /** Gets or sets value of DPad right */
  71023. get: function () {
  71024. return this._dPadRight;
  71025. },
  71026. set: function (value) {
  71027. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71028. },
  71029. enumerable: true,
  71030. configurable: true
  71031. });
  71032. /**
  71033. * Force the gamepad to synchronize with device values
  71034. */
  71035. Xbox360Pad.prototype.update = function () {
  71036. _super.prototype.update.call(this);
  71037. if (this._isXboxOnePad) {
  71038. this.buttonA = this.browserGamepad.buttons[0].value;
  71039. this.buttonB = this.browserGamepad.buttons[1].value;
  71040. this.buttonX = this.browserGamepad.buttons[2].value;
  71041. this.buttonY = this.browserGamepad.buttons[3].value;
  71042. this.buttonLB = this.browserGamepad.buttons[4].value;
  71043. this.buttonRB = this.browserGamepad.buttons[5].value;
  71044. this.leftTrigger = this.browserGamepad.axes[2];
  71045. this.rightTrigger = this.browserGamepad.axes[5];
  71046. this.buttonBack = this.browserGamepad.buttons[9].value;
  71047. this.buttonStart = this.browserGamepad.buttons[8].value;
  71048. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71049. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71050. this.dPadUp = this.browserGamepad.buttons[11].value;
  71051. this.dPadDown = this.browserGamepad.buttons[12].value;
  71052. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71053. this.dPadRight = this.browserGamepad.buttons[14].value;
  71054. }
  71055. else {
  71056. this.buttonA = this.browserGamepad.buttons[0].value;
  71057. this.buttonB = this.browserGamepad.buttons[1].value;
  71058. this.buttonX = this.browserGamepad.buttons[2].value;
  71059. this.buttonY = this.browserGamepad.buttons[3].value;
  71060. this.buttonLB = this.browserGamepad.buttons[4].value;
  71061. this.buttonRB = this.browserGamepad.buttons[5].value;
  71062. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71063. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71064. this.buttonBack = this.browserGamepad.buttons[8].value;
  71065. this.buttonStart = this.browserGamepad.buttons[9].value;
  71066. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71067. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71068. this.dPadUp = this.browserGamepad.buttons[12].value;
  71069. this.dPadDown = this.browserGamepad.buttons[13].value;
  71070. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71071. this.dPadRight = this.browserGamepad.buttons[15].value;
  71072. }
  71073. };
  71074. Xbox360Pad.prototype.dispose = function () {
  71075. _super.prototype.dispose.call(this);
  71076. this.onButtonDownObservable.clear();
  71077. this.onButtonUpObservable.clear();
  71078. this.onPadDownObservable.clear();
  71079. this.onPadUpObservable.clear();
  71080. };
  71081. return Xbox360Pad;
  71082. }(BABYLON.Gamepad));
  71083. BABYLON.Xbox360Pad = Xbox360Pad;
  71084. })(BABYLON || (BABYLON = {}));
  71085. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71086. var BABYLON;
  71087. (function (BABYLON) {
  71088. /**
  71089. * Defines the types of pose enabled controllers that are supported
  71090. */
  71091. var PoseEnabledControllerType;
  71092. (function (PoseEnabledControllerType) {
  71093. /**
  71094. * HTC Vive
  71095. */
  71096. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71097. /**
  71098. * Oculus Rift
  71099. */
  71100. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71101. /**
  71102. * Windows mixed reality
  71103. */
  71104. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71105. /**
  71106. * Samsung gear VR
  71107. */
  71108. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71109. /**
  71110. * Google Daydream
  71111. */
  71112. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71113. /**
  71114. * Generic
  71115. */
  71116. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71117. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71118. /**
  71119. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71120. */
  71121. var PoseEnabledControllerHelper = /** @class */ (function () {
  71122. function PoseEnabledControllerHelper() {
  71123. }
  71124. /**
  71125. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71126. * @param vrGamepad the gamepad to initialized
  71127. * @returns a vr controller of the type the gamepad identified as
  71128. */
  71129. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71130. // Oculus Touch
  71131. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71132. return new BABYLON.OculusTouchController(vrGamepad);
  71133. }
  71134. // Windows Mixed Reality controllers
  71135. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71136. return new BABYLON.WindowsMotionController(vrGamepad);
  71137. }
  71138. // HTC Vive
  71139. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71140. return new BABYLON.ViveController(vrGamepad);
  71141. }
  71142. // Samsung/Oculus Gear VR or Oculus Go
  71143. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71144. return new BABYLON.GearVRController(vrGamepad);
  71145. }
  71146. // Google Daydream
  71147. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71148. return new BABYLON.DaydreamController(vrGamepad);
  71149. }
  71150. // Generic
  71151. else {
  71152. return new BABYLON.GenericController(vrGamepad);
  71153. }
  71154. };
  71155. return PoseEnabledControllerHelper;
  71156. }());
  71157. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71158. /**
  71159. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71160. */
  71161. var PoseEnabledController = /** @class */ (function (_super) {
  71162. __extends(PoseEnabledController, _super);
  71163. /**
  71164. * Creates a new PoseEnabledController from a gamepad
  71165. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71166. */
  71167. function PoseEnabledController(browserGamepad) {
  71168. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71169. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71170. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71171. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71172. /**
  71173. * The device position in babylon space
  71174. */
  71175. _this.devicePosition = BABYLON.Vector3.Zero();
  71176. /**
  71177. * The device rotation in babylon space
  71178. */
  71179. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71180. /**
  71181. * The scale factor of the device in babylon space
  71182. */
  71183. _this.deviceScaleFactor = 1;
  71184. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71185. /**
  71186. * Internal, matrix used to convert room space to babylon space
  71187. */
  71188. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71189. /**
  71190. * Node to be used when casting a ray from the controller
  71191. */
  71192. _this._pointingPoseNode = null;
  71193. _this._workingMatrix = BABYLON.Matrix.Identity();
  71194. /**
  71195. * @hidden
  71196. */
  71197. _this._meshAttachedObservable = new BABYLON.Observable();
  71198. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71199. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71200. _this.position = BABYLON.Vector3.Zero();
  71201. _this.rotationQuaternion = new BABYLON.Quaternion();
  71202. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71203. _this._calculatedRotation = new BABYLON.Quaternion();
  71204. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71205. return _this;
  71206. }
  71207. /**
  71208. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71209. */
  71210. PoseEnabledController.prototype.update = function () {
  71211. _super.prototype.update.call(this);
  71212. var pose = this.browserGamepad.pose;
  71213. this.updateFromDevice(pose);
  71214. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71215. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71216. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71217. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71218. if (this._mesh) {
  71219. this._mesh.position.copyFrom(this.devicePosition);
  71220. if (this._mesh.rotationQuaternion) {
  71221. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71222. }
  71223. }
  71224. };
  71225. /**
  71226. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71227. * @param poseData raw pose fromthe device
  71228. */
  71229. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71230. if (poseData) {
  71231. this.rawPose = poseData;
  71232. if (poseData.position) {
  71233. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71234. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71235. this._deviceRoomPosition.z *= -1;
  71236. }
  71237. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71238. this._calculatedPosition.addInPlace(this.position);
  71239. }
  71240. var pose = this.rawPose;
  71241. if (poseData.orientation && pose.orientation) {
  71242. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71243. if (this._mesh) {
  71244. if (this._mesh.getScene().useRightHandedSystem) {
  71245. this._deviceRoomRotationQuaternion.z *= -1;
  71246. this._deviceRoomRotationQuaternion.w *= -1;
  71247. }
  71248. else {
  71249. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71250. }
  71251. }
  71252. // if the camera is set, rotate to the camera's rotation
  71253. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71254. }
  71255. }
  71256. };
  71257. /**
  71258. * Attaches a mesh to the controller
  71259. * @param mesh the mesh to be attached
  71260. */
  71261. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71262. if (this._mesh) {
  71263. this._mesh.parent = null;
  71264. }
  71265. this._mesh = mesh;
  71266. if (this._poseControlledCamera) {
  71267. this._mesh.parent = this._poseControlledCamera;
  71268. }
  71269. if (!this._mesh.rotationQuaternion) {
  71270. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71271. }
  71272. this._meshAttachedObservable.notifyObservers(mesh);
  71273. };
  71274. /**
  71275. * Attaches the controllers mesh to a camera
  71276. * @param camera the camera the mesh should be attached to
  71277. */
  71278. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71279. this._poseControlledCamera = camera;
  71280. if (this._mesh) {
  71281. this._mesh.parent = this._poseControlledCamera;
  71282. }
  71283. };
  71284. /**
  71285. * Disposes of the controller
  71286. */
  71287. PoseEnabledController.prototype.dispose = function () {
  71288. if (this._mesh) {
  71289. this._mesh.dispose();
  71290. }
  71291. this._mesh = null;
  71292. _super.prototype.dispose.call(this);
  71293. };
  71294. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71295. /**
  71296. * The mesh that is attached to the controller
  71297. */
  71298. get: function () {
  71299. return this._mesh;
  71300. },
  71301. enumerable: true,
  71302. configurable: true
  71303. });
  71304. /**
  71305. * Gets the ray of the controller in the direction the controller is pointing
  71306. * @param length the length the resulting ray should be
  71307. * @returns a ray in the direction the controller is pointing
  71308. */
  71309. PoseEnabledController.prototype.getForwardRay = function (length) {
  71310. if (length === void 0) { length = 100; }
  71311. if (!this.mesh) {
  71312. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71313. }
  71314. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71315. var origin = m.getTranslation();
  71316. var forward = new BABYLON.Vector3(0, 0, -1);
  71317. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71318. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71319. return new BABYLON.Ray(origin, direction, length);
  71320. };
  71321. /**
  71322. * Name of the child mesh that can be used to cast a ray from the controller
  71323. */
  71324. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71325. return PoseEnabledController;
  71326. }(BABYLON.Gamepad));
  71327. BABYLON.PoseEnabledController = PoseEnabledController;
  71328. })(BABYLON || (BABYLON = {}));
  71329. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71330. var BABYLON;
  71331. (function (BABYLON) {
  71332. /**
  71333. * Defines the WebVRController object that represents controllers tracked in 3D space
  71334. */
  71335. var WebVRController = /** @class */ (function (_super) {
  71336. __extends(WebVRController, _super);
  71337. /**
  71338. * Creates a new WebVRController from a gamepad
  71339. * @param vrGamepad the gamepad that the WebVRController should be created from
  71340. */
  71341. function WebVRController(vrGamepad) {
  71342. var _this = _super.call(this, vrGamepad) || this;
  71343. // Observables
  71344. /**
  71345. * Fired when the trigger state has changed
  71346. */
  71347. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71348. /**
  71349. * Fired when the main button state has changed
  71350. */
  71351. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71352. /**
  71353. * Fired when the secondary button state has changed
  71354. */
  71355. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71356. /**
  71357. * Fired when the pad state has changed
  71358. */
  71359. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71360. /**
  71361. * Fired when controllers stick values have changed
  71362. */
  71363. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71364. /**
  71365. * X and Y axis corrisponding to the controllers joystick
  71366. */
  71367. _this.pad = { x: 0, y: 0 };
  71368. // avoid GC, store state in a tmp object
  71369. _this._changes = {
  71370. pressChanged: false,
  71371. touchChanged: false,
  71372. valueChanged: false,
  71373. changed: false
  71374. };
  71375. _this._buttons = new Array(vrGamepad.buttons.length);
  71376. _this.hand = vrGamepad.hand;
  71377. return _this;
  71378. }
  71379. /**
  71380. * Fired when a controller button's state has changed
  71381. * @param callback the callback containing the button that was modified
  71382. */
  71383. WebVRController.prototype.onButtonStateChange = function (callback) {
  71384. this._onButtonStateChange = callback;
  71385. };
  71386. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71387. /**
  71388. * The default controller model for the controller
  71389. */
  71390. get: function () {
  71391. return this._defaultModel;
  71392. },
  71393. enumerable: true,
  71394. configurable: true
  71395. });
  71396. /**
  71397. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71398. */
  71399. WebVRController.prototype.update = function () {
  71400. _super.prototype.update.call(this);
  71401. for (var index = 0; index < this._buttons.length; index++) {
  71402. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71403. }
  71404. ;
  71405. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71406. this.pad.x = this.leftStick.x;
  71407. this.pad.y = this.leftStick.y;
  71408. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71409. }
  71410. };
  71411. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71412. if (!newState) {
  71413. newState = {
  71414. pressed: false,
  71415. touched: false,
  71416. value: 0
  71417. };
  71418. }
  71419. if (!currentState) {
  71420. this._buttons[buttonIndex] = {
  71421. pressed: newState.pressed,
  71422. touched: newState.touched,
  71423. value: newState.value
  71424. };
  71425. return;
  71426. }
  71427. this._checkChanges(newState, currentState);
  71428. if (this._changes.changed) {
  71429. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71430. this._handleButtonChange(buttonIndex, newState, this._changes);
  71431. }
  71432. this._buttons[buttonIndex].pressed = newState.pressed;
  71433. this._buttons[buttonIndex].touched = newState.touched;
  71434. // oculus triggers are never 0, thou not touched.
  71435. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71436. };
  71437. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71438. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71439. this._changes.touchChanged = newState.touched !== currentState.touched;
  71440. this._changes.valueChanged = newState.value !== currentState.value;
  71441. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71442. return this._changes;
  71443. };
  71444. /**
  71445. * Disposes of th webVRCOntroller
  71446. */
  71447. WebVRController.prototype.dispose = function () {
  71448. _super.prototype.dispose.call(this);
  71449. this.onTriggerStateChangedObservable.clear();
  71450. this.onMainButtonStateChangedObservable.clear();
  71451. this.onSecondaryButtonStateChangedObservable.clear();
  71452. this.onPadStateChangedObservable.clear();
  71453. this.onPadValuesChangedObservable.clear();
  71454. };
  71455. return WebVRController;
  71456. }(BABYLON.PoseEnabledController));
  71457. BABYLON.WebVRController = WebVRController;
  71458. })(BABYLON || (BABYLON = {}));
  71459. //# sourceMappingURL=babylon.webVRController.js.map
  71460. var BABYLON;
  71461. (function (BABYLON) {
  71462. /**
  71463. * Oculus Touch Controller
  71464. */
  71465. var OculusTouchController = /** @class */ (function (_super) {
  71466. __extends(OculusTouchController, _super);
  71467. /**
  71468. * Creates a new OculusTouchController from a gamepad
  71469. * @param vrGamepad the gamepad that the controller should be created from
  71470. */
  71471. function OculusTouchController(vrGamepad) {
  71472. var _this = _super.call(this, vrGamepad) || this;
  71473. /**
  71474. * Fired when the secondary trigger on this controller is modified
  71475. */
  71476. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71477. /**
  71478. * Fired when the thumb rest on this controller is modified
  71479. */
  71480. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71481. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71482. return _this;
  71483. }
  71484. /**
  71485. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71486. * @param scene scene in which to add meshes
  71487. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71488. */
  71489. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71490. var _this = this;
  71491. var meshName;
  71492. // Hand
  71493. if (this.hand === 'left') {
  71494. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71495. }
  71496. else { // Right is the default if no hand is specified
  71497. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71498. }
  71499. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71500. /*
  71501. Parent Mesh name: oculus_touch_left
  71502. - body
  71503. - trigger
  71504. - thumbstick
  71505. - grip
  71506. - button_y
  71507. - button_x
  71508. - button_enter
  71509. */
  71510. _this._defaultModel = newMeshes[1];
  71511. _this.attachToMesh(_this._defaultModel);
  71512. if (meshLoaded) {
  71513. meshLoaded(_this._defaultModel);
  71514. }
  71515. });
  71516. };
  71517. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71518. /**
  71519. * Fired when the A button on this controller is modified
  71520. */
  71521. get: function () {
  71522. if (this.hand === 'right') {
  71523. return this.onMainButtonStateChangedObservable;
  71524. }
  71525. else {
  71526. throw new Error('No A button on left hand');
  71527. }
  71528. },
  71529. enumerable: true,
  71530. configurable: true
  71531. });
  71532. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71533. /**
  71534. * Fired when the B button on this controller is modified
  71535. */
  71536. get: function () {
  71537. if (this.hand === 'right') {
  71538. return this.onSecondaryButtonStateChangedObservable;
  71539. }
  71540. else {
  71541. throw new Error('No B button on left hand');
  71542. }
  71543. },
  71544. enumerable: true,
  71545. configurable: true
  71546. });
  71547. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71548. /**
  71549. * Fired when the X button on this controller is modified
  71550. */
  71551. get: function () {
  71552. if (this.hand === 'left') {
  71553. return this.onMainButtonStateChangedObservable;
  71554. }
  71555. else {
  71556. throw new Error('No X button on right hand');
  71557. }
  71558. },
  71559. enumerable: true,
  71560. configurable: true
  71561. });
  71562. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71563. /**
  71564. * Fired when the Y button on this controller is modified
  71565. */
  71566. get: function () {
  71567. if (this.hand === 'left') {
  71568. return this.onSecondaryButtonStateChangedObservable;
  71569. }
  71570. else {
  71571. throw new Error('No Y button on right hand');
  71572. }
  71573. },
  71574. enumerable: true,
  71575. configurable: true
  71576. });
  71577. /**
  71578. * Called once for each button that changed state since the last frame
  71579. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71580. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71581. * 2) secondary trigger (same)
  71582. * 3) A (right) X (left), touch, pressed = value
  71583. * 4) B / Y
  71584. * 5) thumb rest
  71585. * @param buttonIdx Which button index changed
  71586. * @param state New state of the button
  71587. * @param changes Which properties on the state changed since last frame
  71588. */
  71589. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71590. var notifyObject = state; //{ state: state, changes: changes };
  71591. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71592. switch (buttonIdx) {
  71593. case 0:
  71594. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71595. return;
  71596. case 1: // index trigger
  71597. if (this._defaultModel) {
  71598. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71599. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71600. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71601. }
  71602. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71603. return;
  71604. case 2: // secondary trigger
  71605. if (this._defaultModel) {
  71606. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71607. }
  71608. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71609. return;
  71610. case 3:
  71611. if (this._defaultModel) {
  71612. if (notifyObject.pressed) {
  71613. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71614. }
  71615. else {
  71616. (this._defaultModel.getChildren()[1]).position.y = 0;
  71617. }
  71618. }
  71619. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71620. return;
  71621. case 4:
  71622. if (this._defaultModel) {
  71623. if (notifyObject.pressed) {
  71624. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71625. }
  71626. else {
  71627. (this._defaultModel.getChildren()[2]).position.y = 0;
  71628. }
  71629. }
  71630. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71631. return;
  71632. case 5:
  71633. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71634. return;
  71635. }
  71636. };
  71637. /**
  71638. * Base Url for the controller model.
  71639. */
  71640. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71641. /**
  71642. * File name for the left controller model.
  71643. */
  71644. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71645. /**
  71646. * File name for the right controller model.
  71647. */
  71648. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71649. return OculusTouchController;
  71650. }(BABYLON.WebVRController));
  71651. BABYLON.OculusTouchController = OculusTouchController;
  71652. })(BABYLON || (BABYLON = {}));
  71653. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71654. var BABYLON;
  71655. (function (BABYLON) {
  71656. /**
  71657. * Vive Controller
  71658. */
  71659. var ViveController = /** @class */ (function (_super) {
  71660. __extends(ViveController, _super);
  71661. /**
  71662. * Creates a new ViveController from a gamepad
  71663. * @param vrGamepad the gamepad that the controller should be created from
  71664. */
  71665. function ViveController(vrGamepad) {
  71666. var _this = _super.call(this, vrGamepad) || this;
  71667. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71668. _this._invertLeftStickY = true;
  71669. return _this;
  71670. }
  71671. /**
  71672. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71673. * @param scene scene in which to add meshes
  71674. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71675. */
  71676. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71677. var _this = this;
  71678. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71679. /*
  71680. Parent Mesh name: ViveWand
  71681. - body
  71682. - r_gripper
  71683. - l_gripper
  71684. - menu_button
  71685. - system_button
  71686. - trackpad
  71687. - trigger
  71688. - LED
  71689. */
  71690. _this._defaultModel = newMeshes[1];
  71691. _this.attachToMesh(_this._defaultModel);
  71692. if (meshLoaded) {
  71693. meshLoaded(_this._defaultModel);
  71694. }
  71695. });
  71696. };
  71697. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71698. /**
  71699. * Fired when the left button on this controller is modified
  71700. */
  71701. get: function () {
  71702. return this.onMainButtonStateChangedObservable;
  71703. },
  71704. enumerable: true,
  71705. configurable: true
  71706. });
  71707. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71708. /**
  71709. * Fired when the right button on this controller is modified
  71710. */
  71711. get: function () {
  71712. return this.onMainButtonStateChangedObservable;
  71713. },
  71714. enumerable: true,
  71715. configurable: true
  71716. });
  71717. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71718. /**
  71719. * Fired when the menu button on this controller is modified
  71720. */
  71721. get: function () {
  71722. return this.onSecondaryButtonStateChangedObservable;
  71723. },
  71724. enumerable: true,
  71725. configurable: true
  71726. });
  71727. /**
  71728. * Called once for each button that changed state since the last frame
  71729. * Vive mapping:
  71730. * 0: touchpad
  71731. * 1: trigger
  71732. * 2: left AND right buttons
  71733. * 3: menu button
  71734. * @param buttonIdx Which button index changed
  71735. * @param state New state of the button
  71736. * @param changes Which properties on the state changed since last frame
  71737. */
  71738. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71739. var notifyObject = state; //{ state: state, changes: changes };
  71740. switch (buttonIdx) {
  71741. case 0:
  71742. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71743. return;
  71744. case 1: // index trigger
  71745. if (this._defaultModel) {
  71746. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71747. }
  71748. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71749. return;
  71750. case 2: // left AND right button
  71751. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71752. return;
  71753. case 3:
  71754. if (this._defaultModel) {
  71755. if (notifyObject.pressed) {
  71756. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71757. }
  71758. else {
  71759. (this._defaultModel.getChildren()[2]).position.y = 0;
  71760. }
  71761. }
  71762. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71763. return;
  71764. }
  71765. };
  71766. /**
  71767. * Base Url for the controller model.
  71768. */
  71769. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71770. /**
  71771. * File name for the controller model.
  71772. */
  71773. ViveController.MODEL_FILENAME = 'wand.babylon';
  71774. return ViveController;
  71775. }(BABYLON.WebVRController));
  71776. BABYLON.ViveController = ViveController;
  71777. })(BABYLON || (BABYLON = {}));
  71778. //# sourceMappingURL=babylon.viveController.js.map
  71779. var BABYLON;
  71780. (function (BABYLON) {
  71781. /**
  71782. * Generic Controller
  71783. */
  71784. var GenericController = /** @class */ (function (_super) {
  71785. __extends(GenericController, _super);
  71786. /**
  71787. * Creates a new GenericController from a gamepad
  71788. * @param vrGamepad the gamepad that the controller should be created from
  71789. */
  71790. function GenericController(vrGamepad) {
  71791. return _super.call(this, vrGamepad) || this;
  71792. }
  71793. /**
  71794. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71795. * @param scene scene in which to add meshes
  71796. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71797. */
  71798. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71799. var _this = this;
  71800. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71801. _this._defaultModel = newMeshes[1];
  71802. _this.attachToMesh(_this._defaultModel);
  71803. if (meshLoaded) {
  71804. meshLoaded(_this._defaultModel);
  71805. }
  71806. });
  71807. };
  71808. /**
  71809. * Called once for each button that changed state since the last frame
  71810. * @param buttonIdx Which button index changed
  71811. * @param state New state of the button
  71812. * @param changes Which properties on the state changed since last frame
  71813. */
  71814. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71815. console.log("Button id: " + buttonIdx + "state: ");
  71816. console.dir(state);
  71817. };
  71818. /**
  71819. * Base Url for the controller model.
  71820. */
  71821. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71822. /**
  71823. * File name for the controller model.
  71824. */
  71825. GenericController.MODEL_FILENAME = 'generic.babylon';
  71826. return GenericController;
  71827. }(BABYLON.WebVRController));
  71828. BABYLON.GenericController = GenericController;
  71829. })(BABYLON || (BABYLON = {}));
  71830. //# sourceMappingURL=babylon.genericController.js.map
  71831. var BABYLON;
  71832. (function (BABYLON) {
  71833. /**
  71834. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71835. */
  71836. var LoadedMeshInfo = /** @class */ (function () {
  71837. function LoadedMeshInfo() {
  71838. /**
  71839. * Map of the button meshes contained in the controller
  71840. */
  71841. this.buttonMeshes = {};
  71842. /**
  71843. * Map of the axis meshes contained in the controller
  71844. */
  71845. this.axisMeshes = {};
  71846. }
  71847. return LoadedMeshInfo;
  71848. }());
  71849. /**
  71850. * Defines the WindowsMotionController object that the state of the windows motion controller
  71851. */
  71852. var WindowsMotionController = /** @class */ (function (_super) {
  71853. __extends(WindowsMotionController, _super);
  71854. /**
  71855. * Creates a new WindowsMotionController from a gamepad
  71856. * @param vrGamepad the gamepad that the controller should be created from
  71857. */
  71858. function WindowsMotionController(vrGamepad) {
  71859. var _this = _super.call(this, vrGamepad) || this;
  71860. _this._mapping = {
  71861. // Semantic button names
  71862. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71863. // A mapping of the button name to glTF model node name
  71864. // that should be transformed by button value.
  71865. buttonMeshNames: {
  71866. 'trigger': 'SELECT',
  71867. 'menu': 'MENU',
  71868. 'grip': 'GRASP',
  71869. 'thumbstick': 'THUMBSTICK_PRESS',
  71870. 'trackpad': 'TOUCHPAD_PRESS'
  71871. },
  71872. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71873. buttonObservableNames: {
  71874. 'trigger': 'onTriggerStateChangedObservable',
  71875. 'menu': 'onSecondaryButtonStateChangedObservable',
  71876. 'grip': 'onMainButtonStateChangedObservable',
  71877. 'thumbstick': 'onPadStateChangedObservable',
  71878. 'trackpad': 'onTrackpadChangedObservable'
  71879. },
  71880. // A mapping of the axis name to glTF model node name
  71881. // that should be transformed by axis value.
  71882. // This array mirrors the browserGamepad.axes array, such that
  71883. // the mesh corresponding to axis 0 is in this array index 0.
  71884. axisMeshNames: [
  71885. 'THUMBSTICK_X',
  71886. 'THUMBSTICK_Y',
  71887. 'TOUCHPAD_TOUCH_X',
  71888. 'TOUCHPAD_TOUCH_Y'
  71889. ],
  71890. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71891. };
  71892. /**
  71893. * Fired when the trackpad on this controller is clicked
  71894. */
  71895. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71896. /**
  71897. * Fired when the trackpad on this controller is modified
  71898. */
  71899. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71900. /**
  71901. * The current x and y values of this controller's trackpad
  71902. */
  71903. _this.trackpad = { x: 0, y: 0 };
  71904. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71905. _this._loadedMeshInfo = null;
  71906. return _this;
  71907. }
  71908. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71909. /**
  71910. * Fired when the trigger on this controller is modified
  71911. */
  71912. get: function () {
  71913. return this.onTriggerStateChangedObservable;
  71914. },
  71915. enumerable: true,
  71916. configurable: true
  71917. });
  71918. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71919. /**
  71920. * Fired when the menu button on this controller is modified
  71921. */
  71922. get: function () {
  71923. return this.onSecondaryButtonStateChangedObservable;
  71924. },
  71925. enumerable: true,
  71926. configurable: true
  71927. });
  71928. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71929. /**
  71930. * Fired when the grip button on this controller is modified
  71931. */
  71932. get: function () {
  71933. return this.onMainButtonStateChangedObservable;
  71934. },
  71935. enumerable: true,
  71936. configurable: true
  71937. });
  71938. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71939. /**
  71940. * Fired when the thumbstick button on this controller is modified
  71941. */
  71942. get: function () {
  71943. return this.onPadStateChangedObservable;
  71944. },
  71945. enumerable: true,
  71946. configurable: true
  71947. });
  71948. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71949. /**
  71950. * Fired when the touchpad button on this controller is modified
  71951. */
  71952. get: function () {
  71953. return this.onTrackpadChangedObservable;
  71954. },
  71955. enumerable: true,
  71956. configurable: true
  71957. });
  71958. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71959. /**
  71960. * Fired when the touchpad values on this controller are modified
  71961. */
  71962. get: function () {
  71963. return this.onTrackpadValuesChangedObservable;
  71964. },
  71965. enumerable: true,
  71966. configurable: true
  71967. });
  71968. /**
  71969. * Called once per frame by the engine.
  71970. */
  71971. WindowsMotionController.prototype.update = function () {
  71972. _super.prototype.update.call(this);
  71973. if (this.browserGamepad.axes) {
  71974. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71975. this.trackpad.x = this.browserGamepad["axes"][2];
  71976. this.trackpad.y = this.browserGamepad["axes"][3];
  71977. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71978. }
  71979. // Only need to animate axes if there is a loaded mesh
  71980. if (this._loadedMeshInfo) {
  71981. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71982. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71983. }
  71984. }
  71985. }
  71986. };
  71987. /**
  71988. * Called once for each button that changed state since the last frame
  71989. * @param buttonIdx Which button index changed
  71990. * @param state New state of the button
  71991. * @param changes Which properties on the state changed since last frame
  71992. */
  71993. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71994. var buttonName = this._mapping.buttons[buttonIdx];
  71995. if (!buttonName) {
  71996. return;
  71997. }
  71998. // Only emit events for buttons that we know how to map from index to name
  71999. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72000. if (observable) {
  72001. observable.notifyObservers(state);
  72002. }
  72003. this._lerpButtonTransform(buttonName, state.value);
  72004. };
  72005. /**
  72006. * Moves the buttons on the controller mesh based on their current state
  72007. * @param buttonName the name of the button to move
  72008. * @param buttonValue the value of the button which determines the buttons new position
  72009. */
  72010. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72011. // If there is no loaded mesh, there is nothing to transform.
  72012. if (!this._loadedMeshInfo) {
  72013. return;
  72014. }
  72015. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72016. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72017. return;
  72018. }
  72019. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72020. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72021. };
  72022. /**
  72023. * Moves the axis on the controller mesh based on its current state
  72024. * @param axis the index of the axis
  72025. * @param axisValue the value of the axis which determines the meshes new position
  72026. * @hidden
  72027. */
  72028. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72029. if (!this._loadedMeshInfo) {
  72030. return;
  72031. }
  72032. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72033. if (!meshInfo) {
  72034. return;
  72035. }
  72036. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72037. return;
  72038. }
  72039. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72040. var lerpValue = axisValue * 0.5 + 0.5;
  72041. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72042. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72043. };
  72044. /**
  72045. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72046. * @param scene scene in which to add meshes
  72047. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72048. */
  72049. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72050. var _this = this;
  72051. if (forceDefault === void 0) { forceDefault = false; }
  72052. var path;
  72053. var filename;
  72054. // Checking if GLB loader is present
  72055. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72056. // Determine the device specific folder based on the ID suffix
  72057. var device = 'default';
  72058. if (this.id && !forceDefault) {
  72059. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72060. device = ((match && match[0]) || device);
  72061. }
  72062. // Hand
  72063. if (this.hand === 'left') {
  72064. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72065. }
  72066. else { // Right is the default if no hand is specified
  72067. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72068. }
  72069. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72070. }
  72071. else {
  72072. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72073. path = BABYLON.GenericController.MODEL_BASE_URL;
  72074. filename = BABYLON.GenericController.MODEL_FILENAME;
  72075. }
  72076. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72077. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72078. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72079. if (!_this._loadedMeshInfo) {
  72080. return;
  72081. }
  72082. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72083. _this.attachToMesh(_this._defaultModel);
  72084. if (meshLoaded) {
  72085. meshLoaded(_this._defaultModel);
  72086. }
  72087. }, null, function (scene, message) {
  72088. BABYLON.Tools.Log(message);
  72089. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72090. if (!forceDefault) {
  72091. _this.initControllerMesh(scene, meshLoaded, true);
  72092. }
  72093. });
  72094. };
  72095. /**
  72096. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72097. * can be transformed by button presses and axes values, based on this._mapping.
  72098. *
  72099. * @param scene scene in which the meshes exist
  72100. * @param meshes list of meshes that make up the controller model to process
  72101. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72102. */
  72103. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72104. var loadedMeshInfo = null;
  72105. // Create a new mesh to contain the glTF hierarchy
  72106. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72107. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72108. var childMesh = null;
  72109. for (var i = 0; i < meshes.length; i++) {
  72110. var mesh = meshes[i];
  72111. if (!mesh.parent) {
  72112. // Exclude controller meshes from picking results
  72113. mesh.isPickable = false;
  72114. // Handle root node, attach to the new parentMesh
  72115. childMesh = mesh;
  72116. break;
  72117. }
  72118. }
  72119. if (childMesh) {
  72120. childMesh.setParent(parentMesh);
  72121. // Create our mesh info. Note that this method will always return non-null.
  72122. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72123. }
  72124. else {
  72125. BABYLON.Tools.Warn('Could not find root node in model file.');
  72126. }
  72127. return loadedMeshInfo;
  72128. };
  72129. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72130. var loadedMeshInfo = new LoadedMeshInfo();
  72131. var i;
  72132. loadedMeshInfo.rootNode = rootNode;
  72133. // Reset the caches
  72134. loadedMeshInfo.buttonMeshes = {};
  72135. loadedMeshInfo.axisMeshes = {};
  72136. // Button Meshes
  72137. for (i = 0; i < this._mapping.buttons.length; i++) {
  72138. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72139. if (!buttonMeshName) {
  72140. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72141. continue;
  72142. }
  72143. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72144. if (!buttonMesh) {
  72145. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72146. continue;
  72147. }
  72148. var buttonMeshInfo = {
  72149. index: i,
  72150. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72151. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72152. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72153. };
  72154. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72155. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72156. }
  72157. else {
  72158. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72159. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72160. '(VALUE: ' + !!buttonMeshInfo.value +
  72161. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72162. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72163. ')');
  72164. }
  72165. }
  72166. // Axis Meshes
  72167. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72168. var axisMeshName = this._mapping.axisMeshNames[i];
  72169. if (!axisMeshName) {
  72170. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72171. continue;
  72172. }
  72173. var axisMesh = getChildByName(rootNode, axisMeshName);
  72174. if (!axisMesh) {
  72175. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72176. continue;
  72177. }
  72178. var axisMeshInfo = {
  72179. index: i,
  72180. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72181. min: getImmediateChildByName(axisMesh, 'MIN'),
  72182. max: getImmediateChildByName(axisMesh, 'MAX')
  72183. };
  72184. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72185. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72186. }
  72187. else {
  72188. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72189. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72190. '(VALUE: ' + !!axisMeshInfo.value +
  72191. ', MIN: ' + !!axisMeshInfo.min +
  72192. ', MAX:' + !!axisMeshInfo.max +
  72193. ')');
  72194. }
  72195. }
  72196. // Pointing Ray
  72197. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72198. if (!loadedMeshInfo.pointingPoseNode) {
  72199. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72200. }
  72201. return loadedMeshInfo;
  72202. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72203. function getChildByName(node, name) {
  72204. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72205. }
  72206. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72207. function getImmediateChildByName(node, name) {
  72208. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72209. }
  72210. };
  72211. /**
  72212. * Gets the ray of the controller in the direction the controller is pointing
  72213. * @param length the length the resulting ray should be
  72214. * @returns a ray in the direction the controller is pointing
  72215. */
  72216. WindowsMotionController.prototype.getForwardRay = function (length) {
  72217. if (length === void 0) { length = 100; }
  72218. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72219. return _super.prototype.getForwardRay.call(this, length);
  72220. }
  72221. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72222. var origin = m.getTranslation();
  72223. var forward = new BABYLON.Vector3(0, 0, -1);
  72224. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72225. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72226. return new BABYLON.Ray(origin, direction, length);
  72227. };
  72228. /**
  72229. * Disposes of the controller
  72230. */
  72231. WindowsMotionController.prototype.dispose = function () {
  72232. _super.prototype.dispose.call(this);
  72233. this.onTrackpadChangedObservable.clear();
  72234. };
  72235. /**
  72236. * The base url used to load the left and right controller models
  72237. */
  72238. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72239. /**
  72240. * The name of the left controller model file
  72241. */
  72242. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72243. /**
  72244. * The name of the right controller model file
  72245. */
  72246. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72247. /**
  72248. * The controller name prefix for this controller type
  72249. */
  72250. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72251. /**
  72252. * The controller id pattern for this controller type
  72253. */
  72254. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72255. return WindowsMotionController;
  72256. }(BABYLON.WebVRController));
  72257. BABYLON.WindowsMotionController = WindowsMotionController;
  72258. })(BABYLON || (BABYLON = {}));
  72259. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72260. var BABYLON;
  72261. (function (BABYLON) {
  72262. /**
  72263. * Gear VR Controller
  72264. */
  72265. var GearVRController = /** @class */ (function (_super) {
  72266. __extends(GearVRController, _super);
  72267. /**
  72268. * Creates a new GearVRController from a gamepad
  72269. * @param vrGamepad the gamepad that the controller should be created from
  72270. */
  72271. function GearVRController(vrGamepad) {
  72272. var _this = _super.call(this, vrGamepad) || this;
  72273. _this._buttonIndexToObservableNameMap = [
  72274. 'onTrackpadChangedObservable',
  72275. 'onTriggerStateChangedObservable' // Trigger
  72276. ];
  72277. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72278. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72279. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72280. return _this;
  72281. }
  72282. /**
  72283. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72284. * @param scene scene in which to add meshes
  72285. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72286. */
  72287. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72288. var _this = this;
  72289. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72290. _this._defaultModel = newMeshes[1];
  72291. _this.attachToMesh(_this._defaultModel);
  72292. if (meshLoaded) {
  72293. meshLoaded(_this._defaultModel);
  72294. }
  72295. });
  72296. };
  72297. /**
  72298. * Called once for each button that changed state since the last frame
  72299. * @param buttonIdx Which button index changed
  72300. * @param state New state of the button
  72301. * @param changes Which properties on the state changed since last frame
  72302. */
  72303. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72304. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72305. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72306. // Only emit events for buttons that we know how to map from index to observable
  72307. var observable = this[observableName];
  72308. if (observable) {
  72309. observable.notifyObservers(state);
  72310. }
  72311. }
  72312. };
  72313. /**
  72314. * Base Url for the controller model.
  72315. */
  72316. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72317. /**
  72318. * File name for the controller model.
  72319. */
  72320. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72321. /**
  72322. * Gamepad Id prefix used to identify this controller.
  72323. */
  72324. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72325. return GearVRController;
  72326. }(BABYLON.WebVRController));
  72327. BABYLON.GearVRController = GearVRController;
  72328. })(BABYLON || (BABYLON = {}));
  72329. //# sourceMappingURL=babylon.gearVRController.js.map
  72330. var BABYLON;
  72331. (function (BABYLON) {
  72332. /**
  72333. * Google Daydream controller
  72334. */
  72335. var DaydreamController = /** @class */ (function (_super) {
  72336. __extends(DaydreamController, _super);
  72337. /**
  72338. * Creates a new DaydreamController from a gamepad
  72339. * @param vrGamepad the gamepad that the controller should be created from
  72340. */
  72341. function DaydreamController(vrGamepad) {
  72342. var _this = _super.call(this, vrGamepad) || this;
  72343. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72344. return _this;
  72345. }
  72346. /**
  72347. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72348. * @param scene scene in which to add meshes
  72349. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72350. */
  72351. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72352. var _this = this;
  72353. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72354. _this._defaultModel = newMeshes[1];
  72355. _this.attachToMesh(_this._defaultModel);
  72356. if (meshLoaded) {
  72357. meshLoaded(_this._defaultModel);
  72358. }
  72359. });
  72360. };
  72361. /**
  72362. * Called once for each button that changed state since the last frame
  72363. * @param buttonIdx Which button index changed
  72364. * @param state New state of the button
  72365. * @param changes Which properties on the state changed since last frame
  72366. */
  72367. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72368. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72369. if (buttonIdx === 0) {
  72370. var observable = this.onTriggerStateChangedObservable;
  72371. if (observable) {
  72372. observable.notifyObservers(state);
  72373. }
  72374. }
  72375. else {
  72376. // If the app or home buttons are ever made available
  72377. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72378. }
  72379. };
  72380. /**
  72381. * Base Url for the controller model.
  72382. */
  72383. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72384. /**
  72385. * File name for the controller model.
  72386. */
  72387. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72388. /**
  72389. * Gamepad Id prefix used to identify Daydream Controller.
  72390. */
  72391. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72392. return DaydreamController;
  72393. }(BABYLON.WebVRController));
  72394. BABYLON.DaydreamController = DaydreamController;
  72395. })(BABYLON || (BABYLON = {}));
  72396. //# sourceMappingURL=babylon.daydreamController.js.map
  72397. var BABYLON;
  72398. (function (BABYLON) {
  72399. var FollowCamera = /** @class */ (function (_super) {
  72400. __extends(FollowCamera, _super);
  72401. function FollowCamera(name, position, scene, lockedTarget) {
  72402. if (lockedTarget === void 0) { lockedTarget = null; }
  72403. var _this = _super.call(this, name, position, scene) || this;
  72404. _this.radius = 12;
  72405. _this.rotationOffset = 0;
  72406. _this.heightOffset = 4;
  72407. _this.cameraAcceleration = 0.05;
  72408. _this.maxCameraSpeed = 20;
  72409. _this.lockedTarget = lockedTarget;
  72410. return _this;
  72411. }
  72412. FollowCamera.prototype.getRadians = function (degrees) {
  72413. return degrees * Math.PI / 180;
  72414. };
  72415. FollowCamera.prototype.follow = function (cameraTarget) {
  72416. if (!cameraTarget)
  72417. return;
  72418. var yRotation;
  72419. if (cameraTarget.rotationQuaternion) {
  72420. var rotMatrix = new BABYLON.Matrix();
  72421. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72422. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72423. }
  72424. else {
  72425. yRotation = cameraTarget.rotation.y;
  72426. }
  72427. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72428. var targetPosition = cameraTarget.getAbsolutePosition();
  72429. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72430. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72431. var dx = targetX - this.position.x;
  72432. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72433. var dz = (targetZ) - this.position.z;
  72434. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72435. var vy = dy * this.cameraAcceleration;
  72436. var vz = dz * this.cameraAcceleration * 2;
  72437. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72438. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72439. }
  72440. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72441. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72442. }
  72443. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72444. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72445. }
  72446. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72447. this.setTarget(targetPosition);
  72448. };
  72449. FollowCamera.prototype._checkInputs = function () {
  72450. _super.prototype._checkInputs.call(this);
  72451. if (this.lockedTarget) {
  72452. this.follow(this.lockedTarget);
  72453. }
  72454. };
  72455. FollowCamera.prototype.getClassName = function () {
  72456. return "FollowCamera";
  72457. };
  72458. __decorate([
  72459. BABYLON.serialize()
  72460. ], FollowCamera.prototype, "radius", void 0);
  72461. __decorate([
  72462. BABYLON.serialize()
  72463. ], FollowCamera.prototype, "rotationOffset", void 0);
  72464. __decorate([
  72465. BABYLON.serialize()
  72466. ], FollowCamera.prototype, "heightOffset", void 0);
  72467. __decorate([
  72468. BABYLON.serialize()
  72469. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72470. __decorate([
  72471. BABYLON.serialize()
  72472. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72473. __decorate([
  72474. BABYLON.serializeAsMeshReference("lockedTargetId")
  72475. ], FollowCamera.prototype, "lockedTarget", void 0);
  72476. return FollowCamera;
  72477. }(BABYLON.TargetCamera));
  72478. BABYLON.FollowCamera = FollowCamera;
  72479. var ArcFollowCamera = /** @class */ (function (_super) {
  72480. __extends(ArcFollowCamera, _super);
  72481. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72482. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72483. _this.alpha = alpha;
  72484. _this.beta = beta;
  72485. _this.radius = radius;
  72486. _this.target = target;
  72487. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72488. _this.follow();
  72489. return _this;
  72490. }
  72491. ArcFollowCamera.prototype.follow = function () {
  72492. if (!this.target) {
  72493. return;
  72494. }
  72495. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72496. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72497. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72498. var targetPosition = this.target.getAbsolutePosition();
  72499. this.position = targetPosition.add(this._cartesianCoordinates);
  72500. this.setTarget(targetPosition);
  72501. };
  72502. ArcFollowCamera.prototype._checkInputs = function () {
  72503. _super.prototype._checkInputs.call(this);
  72504. this.follow();
  72505. };
  72506. ArcFollowCamera.prototype.getClassName = function () {
  72507. return "ArcFollowCamera";
  72508. };
  72509. return ArcFollowCamera;
  72510. }(BABYLON.TargetCamera));
  72511. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72512. })(BABYLON || (BABYLON = {}));
  72513. //# sourceMappingURL=babylon.followCamera.js.map
  72514. var BABYLON;
  72515. (function (BABYLON) {
  72516. // We're mainly based on the logic defined into the FreeCamera code
  72517. var UniversalCamera = /** @class */ (function (_super) {
  72518. __extends(UniversalCamera, _super);
  72519. //-- end properties for backward compatibility for inputs
  72520. function UniversalCamera(name, position, scene) {
  72521. var _this = _super.call(this, name, position, scene) || this;
  72522. _this.inputs.addGamepad();
  72523. return _this;
  72524. }
  72525. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72526. //-- Begin properties for backward compatibility for inputs
  72527. get: function () {
  72528. var gamepad = this.inputs.attached["gamepad"];
  72529. if (gamepad)
  72530. return gamepad.gamepadAngularSensibility;
  72531. return 0;
  72532. },
  72533. set: function (value) {
  72534. var gamepad = this.inputs.attached["gamepad"];
  72535. if (gamepad)
  72536. gamepad.gamepadAngularSensibility = value;
  72537. },
  72538. enumerable: true,
  72539. configurable: true
  72540. });
  72541. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72542. get: function () {
  72543. var gamepad = this.inputs.attached["gamepad"];
  72544. if (gamepad)
  72545. return gamepad.gamepadMoveSensibility;
  72546. return 0;
  72547. },
  72548. set: function (value) {
  72549. var gamepad = this.inputs.attached["gamepad"];
  72550. if (gamepad)
  72551. gamepad.gamepadMoveSensibility = value;
  72552. },
  72553. enumerable: true,
  72554. configurable: true
  72555. });
  72556. UniversalCamera.prototype.getClassName = function () {
  72557. return "UniversalCamera";
  72558. };
  72559. return UniversalCamera;
  72560. }(BABYLON.TouchCamera));
  72561. BABYLON.UniversalCamera = UniversalCamera;
  72562. })(BABYLON || (BABYLON = {}));
  72563. //# sourceMappingURL=babylon.universalCamera.js.map
  72564. var BABYLON;
  72565. (function (BABYLON) {
  72566. // We're mainly based on the logic defined into the FreeCamera code
  72567. var GamepadCamera = /** @class */ (function (_super) {
  72568. __extends(GamepadCamera, _super);
  72569. //-- end properties for backward compatibility for inputs
  72570. function GamepadCamera(name, position, scene) {
  72571. return _super.call(this, name, position, scene) || this;
  72572. }
  72573. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72574. //-- Begin properties for backward compatibility for inputs
  72575. get: function () {
  72576. var gamepad = this.inputs.attached["gamepad"];
  72577. if (gamepad)
  72578. return gamepad.gamepadAngularSensibility;
  72579. return 0;
  72580. },
  72581. set: function (value) {
  72582. var gamepad = this.inputs.attached["gamepad"];
  72583. if (gamepad)
  72584. gamepad.gamepadAngularSensibility = value;
  72585. },
  72586. enumerable: true,
  72587. configurable: true
  72588. });
  72589. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72590. get: function () {
  72591. var gamepad = this.inputs.attached["gamepad"];
  72592. if (gamepad)
  72593. return gamepad.gamepadMoveSensibility;
  72594. return 0;
  72595. },
  72596. set: function (value) {
  72597. var gamepad = this.inputs.attached["gamepad"];
  72598. if (gamepad)
  72599. gamepad.gamepadMoveSensibility = value;
  72600. },
  72601. enumerable: true,
  72602. configurable: true
  72603. });
  72604. GamepadCamera.prototype.getClassName = function () {
  72605. return "GamepadCamera";
  72606. };
  72607. return GamepadCamera;
  72608. }(BABYLON.UniversalCamera));
  72609. BABYLON.GamepadCamera = GamepadCamera;
  72610. })(BABYLON || (BABYLON = {}));
  72611. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72612. var BABYLON;
  72613. (function (BABYLON) {
  72614. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72615. function PostProcessRenderPipelineManager() {
  72616. this._renderPipelines = {};
  72617. }
  72618. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72619. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72620. };
  72621. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72622. if (unique === void 0) { unique = false; }
  72623. var renderPipeline = this._renderPipelines[renderPipelineName];
  72624. if (!renderPipeline) {
  72625. return;
  72626. }
  72627. renderPipeline._attachCameras(cameras, unique);
  72628. };
  72629. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72630. var renderPipeline = this._renderPipelines[renderPipelineName];
  72631. if (!renderPipeline) {
  72632. return;
  72633. }
  72634. renderPipeline._detachCameras(cameras);
  72635. };
  72636. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72637. var renderPipeline = this._renderPipelines[renderPipelineName];
  72638. if (!renderPipeline) {
  72639. return;
  72640. }
  72641. renderPipeline._enableEffect(renderEffectName, cameras);
  72642. };
  72643. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72644. var renderPipeline = this._renderPipelines[renderPipelineName];
  72645. if (!renderPipeline) {
  72646. return;
  72647. }
  72648. renderPipeline._disableEffect(renderEffectName, cameras);
  72649. };
  72650. PostProcessRenderPipelineManager.prototype.update = function () {
  72651. for (var renderPipelineName in this._renderPipelines) {
  72652. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72653. var pipeline = this._renderPipelines[renderPipelineName];
  72654. if (!pipeline.isSupported) {
  72655. pipeline.dispose();
  72656. delete this._renderPipelines[renderPipelineName];
  72657. }
  72658. else {
  72659. pipeline._update();
  72660. }
  72661. }
  72662. }
  72663. };
  72664. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72665. for (var renderPipelineName in this._renderPipelines) {
  72666. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72667. var pipeline = this._renderPipelines[renderPipelineName];
  72668. pipeline._rebuild();
  72669. }
  72670. }
  72671. };
  72672. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72673. for (var renderPipelineName in this._renderPipelines) {
  72674. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72675. var pipeline = this._renderPipelines[renderPipelineName];
  72676. pipeline.dispose();
  72677. }
  72678. }
  72679. };
  72680. return PostProcessRenderPipelineManager;
  72681. }());
  72682. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72683. })(BABYLON || (BABYLON = {}));
  72684. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72685. var BABYLON;
  72686. (function (BABYLON) {
  72687. /**
  72688. * This represents a set of one or more post processes in Babylon.
  72689. * A post process can be used to apply a shader to a texture after it is rendered.
  72690. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72691. */
  72692. var PostProcessRenderEffect = /** @class */ (function () {
  72693. /**
  72694. * Instantiates a post process render effect.
  72695. * A post process can be used to apply a shader to a texture after it is rendered.
  72696. * @param engine The engine the effect is tied to
  72697. * @param name The name of the effect
  72698. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72699. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72700. */
  72701. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72702. this._name = name;
  72703. this._singleInstance = singleInstance || true;
  72704. this._getPostProcesses = getPostProcesses;
  72705. this._cameras = {};
  72706. this._indicesForCamera = {};
  72707. this._postProcesses = {};
  72708. }
  72709. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72710. /**
  72711. * Checks if all the post processes in the effect are supported.
  72712. */
  72713. get: function () {
  72714. for (var index in this._postProcesses) {
  72715. if (this._postProcesses.hasOwnProperty(index)) {
  72716. var pps = this._postProcesses[index];
  72717. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72718. if (!pps[ppIndex].isSupported) {
  72719. return false;
  72720. }
  72721. }
  72722. }
  72723. }
  72724. return true;
  72725. },
  72726. enumerable: true,
  72727. configurable: true
  72728. });
  72729. /**
  72730. * Updates the current state of the effect
  72731. */
  72732. PostProcessRenderEffect.prototype._update = function () {
  72733. };
  72734. /**
  72735. * Attaches the effect on cameras
  72736. * @param cameras The camera to attach to.
  72737. */
  72738. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72739. var _this = this;
  72740. var cameraKey;
  72741. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72742. if (!cams) {
  72743. return;
  72744. }
  72745. for (var i = 0; i < cams.length; i++) {
  72746. var camera = cams[i];
  72747. var cameraName = camera.name;
  72748. if (this._singleInstance) {
  72749. cameraKey = 0;
  72750. }
  72751. else {
  72752. cameraKey = cameraName;
  72753. }
  72754. if (!this._postProcesses[cameraKey]) {
  72755. var postProcess = this._getPostProcesses();
  72756. if (postProcess) {
  72757. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72758. }
  72759. }
  72760. if (!this._indicesForCamera[cameraName]) {
  72761. this._indicesForCamera[cameraName] = [];
  72762. }
  72763. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72764. var index = camera.attachPostProcess(postProcess);
  72765. _this._indicesForCamera[cameraName].push(index);
  72766. });
  72767. if (!this._cameras[cameraName]) {
  72768. this._cameras[cameraName] = camera;
  72769. }
  72770. }
  72771. };
  72772. /**
  72773. * Detatches the effect on cameras
  72774. * @param cameras The camera to detatch from.
  72775. */
  72776. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72777. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72778. if (!cams) {
  72779. return;
  72780. }
  72781. for (var i = 0; i < cams.length; i++) {
  72782. var camera = cams[i];
  72783. var cameraName = camera.name;
  72784. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72785. camera.detachPostProcess(postProcess);
  72786. });
  72787. if (this._cameras[cameraName]) {
  72788. //this._indicesForCamera.splice(index, 1);
  72789. this._cameras[cameraName] = null;
  72790. }
  72791. }
  72792. };
  72793. /**
  72794. * Enables the effect on given cameras
  72795. * @param cameras The camera to enable.
  72796. */
  72797. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72798. var _this = this;
  72799. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72800. if (!cams) {
  72801. return;
  72802. }
  72803. for (var i = 0; i < cams.length; i++) {
  72804. var camera = cams[i];
  72805. var cameraName = camera.name;
  72806. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72807. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72808. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72809. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72810. });
  72811. }
  72812. }
  72813. }
  72814. };
  72815. /**
  72816. * Disables the effect on the given cameras
  72817. * @param cameras The camera to disable.
  72818. */
  72819. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72820. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72821. if (!cams) {
  72822. return;
  72823. }
  72824. for (var i = 0; i < cams.length; i++) {
  72825. var camera = cams[i];
  72826. var cameraName = camera.name;
  72827. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72828. camera.detachPostProcess(postProcess);
  72829. });
  72830. }
  72831. };
  72832. /**
  72833. * Gets a list of the post processes contained in the effect.
  72834. * @param camera The camera to get the post processes on.
  72835. * @returns The list of the post processes in the effect.
  72836. */
  72837. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72838. if (this._singleInstance) {
  72839. return this._postProcesses[0];
  72840. }
  72841. else {
  72842. if (!camera) {
  72843. return null;
  72844. }
  72845. return this._postProcesses[camera.name];
  72846. }
  72847. };
  72848. return PostProcessRenderEffect;
  72849. }());
  72850. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72851. })(BABYLON || (BABYLON = {}));
  72852. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72853. var BABYLON;
  72854. (function (BABYLON) {
  72855. var PostProcessRenderPipeline = /** @class */ (function () {
  72856. function PostProcessRenderPipeline(engine, name) {
  72857. this.engine = engine;
  72858. this._name = name;
  72859. this._renderEffects = {};
  72860. this._renderEffectsForIsolatedPass = new Array();
  72861. this._cameras = [];
  72862. }
  72863. PostProcessRenderPipeline.prototype.getClassName = function () {
  72864. return "PostProcessRenderPipeline";
  72865. };
  72866. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72867. get: function () {
  72868. for (var renderEffectName in this._renderEffects) {
  72869. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72870. if (!this._renderEffects[renderEffectName].isSupported) {
  72871. return false;
  72872. }
  72873. }
  72874. }
  72875. return true;
  72876. },
  72877. enumerable: true,
  72878. configurable: true
  72879. });
  72880. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72881. this._renderEffects[renderEffect._name] = renderEffect;
  72882. };
  72883. // private
  72884. PostProcessRenderPipeline.prototype._rebuild = function () {
  72885. };
  72886. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72887. var renderEffects = this._renderEffects[renderEffectName];
  72888. if (!renderEffects) {
  72889. return;
  72890. }
  72891. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72892. };
  72893. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72894. var renderEffects = this._renderEffects[renderEffectName];
  72895. if (!renderEffects) {
  72896. return;
  72897. }
  72898. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72899. };
  72900. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72901. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72902. if (!cams) {
  72903. return;
  72904. }
  72905. var indicesToDelete = [];
  72906. var i;
  72907. for (i = 0; i < cams.length; i++) {
  72908. var camera = cams[i];
  72909. var cameraName = camera.name;
  72910. if (this._cameras.indexOf(camera) === -1) {
  72911. this._cameras[cameraName] = camera;
  72912. }
  72913. else if (unique) {
  72914. indicesToDelete.push(i);
  72915. }
  72916. }
  72917. for (i = 0; i < indicesToDelete.length; i++) {
  72918. cameras.splice(indicesToDelete[i], 1);
  72919. }
  72920. for (var renderEffectName in this._renderEffects) {
  72921. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72922. this._renderEffects[renderEffectName]._attachCameras(cams);
  72923. }
  72924. }
  72925. };
  72926. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72927. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72928. if (!cams) {
  72929. return;
  72930. }
  72931. for (var renderEffectName in this._renderEffects) {
  72932. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72933. this._renderEffects[renderEffectName]._detachCameras(cams);
  72934. }
  72935. }
  72936. for (var i = 0; i < cams.length; i++) {
  72937. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72938. }
  72939. };
  72940. PostProcessRenderPipeline.prototype._update = function () {
  72941. for (var renderEffectName in this._renderEffects) {
  72942. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72943. this._renderEffects[renderEffectName]._update();
  72944. }
  72945. }
  72946. for (var i = 0; i < this._cameras.length; i++) {
  72947. var cameraName = this._cameras[i].name;
  72948. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72949. this._renderEffectsForIsolatedPass[cameraName]._update();
  72950. }
  72951. }
  72952. };
  72953. PostProcessRenderPipeline.prototype._reset = function () {
  72954. this._renderEffects = {};
  72955. this._renderEffectsForIsolatedPass = new Array();
  72956. };
  72957. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72958. // 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)
  72959. var effectKeys = Object.keys(this._renderEffects);
  72960. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72961. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72962. if (postProcesses) {
  72963. postProcesses[0].samples = sampleCount;
  72964. return true;
  72965. }
  72966. }
  72967. return false;
  72968. };
  72969. PostProcessRenderPipeline.prototype.dispose = function () {
  72970. // Must be implemented by children
  72971. };
  72972. __decorate([
  72973. BABYLON.serialize()
  72974. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72975. return PostProcessRenderPipeline;
  72976. }());
  72977. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72978. })(BABYLON || (BABYLON = {}));
  72979. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72980. var BABYLON;
  72981. (function (BABYLON) {
  72982. /**
  72983. * This represents a depth renderer in Babylon.
  72984. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72985. */
  72986. var DepthRenderer = /** @class */ (function () {
  72987. /**
  72988. * Instantiates a depth renderer
  72989. * @param scene The scene the renderer belongs to
  72990. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72991. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72992. */
  72993. function DepthRenderer(scene, type, camera) {
  72994. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72995. if (camera === void 0) { camera = null; }
  72996. var _this = this;
  72997. this._scene = scene;
  72998. this._camera = camera;
  72999. var engine = scene.getEngine();
  73000. // Render target
  73001. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73002. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73003. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73004. this._depthMap.refreshRate = 1;
  73005. this._depthMap.renderParticles = false;
  73006. this._depthMap.renderList = null;
  73007. // Camera to get depth map from to support multiple concurrent cameras
  73008. this._depthMap.activeCamera = this._camera;
  73009. this._depthMap.ignoreCameraViewport = true;
  73010. this._depthMap.useCameraPostProcesses = false;
  73011. // set default depth value to 1.0 (far away)
  73012. this._depthMap.onClearObservable.add(function (engine) {
  73013. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73014. });
  73015. // Custom render function
  73016. var renderSubMesh = function (subMesh) {
  73017. var mesh = subMesh.getRenderingMesh();
  73018. var scene = _this._scene;
  73019. var engine = scene.getEngine();
  73020. var material = subMesh.getMaterial();
  73021. if (!material) {
  73022. return;
  73023. }
  73024. // Culling and reverse (right handed system)
  73025. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73026. // Managing instances
  73027. var batch = mesh._getInstancesRenderList(subMesh._id);
  73028. if (batch.mustReturn) {
  73029. return;
  73030. }
  73031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73032. var camera = _this._camera || scene.activeCamera;
  73033. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73034. engine.enableEffect(_this._effect);
  73035. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73036. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73037. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73038. // Alpha test
  73039. if (material && material.needAlphaTesting()) {
  73040. var alphaTexture = material.getAlphaTestTexture();
  73041. if (alphaTexture) {
  73042. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73043. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73044. }
  73045. }
  73046. // Bones
  73047. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73048. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73049. }
  73050. // Draw
  73051. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73052. }
  73053. };
  73054. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73055. var index;
  73056. if (depthOnlySubMeshes.length) {
  73057. engine.setColorWrite(false);
  73058. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73059. renderSubMesh(depthOnlySubMeshes.data[index]);
  73060. }
  73061. engine.setColorWrite(true);
  73062. }
  73063. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73064. renderSubMesh(opaqueSubMeshes.data[index]);
  73065. }
  73066. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73067. renderSubMesh(alphaTestSubMeshes.data[index]);
  73068. }
  73069. };
  73070. }
  73071. /**
  73072. * Creates the depth rendering effect and checks if the effect is ready.
  73073. * @param subMesh The submesh to be used to render the depth map of
  73074. * @param useInstances If multiple world instances should be used
  73075. * @returns if the depth renderer is ready to render the depth map
  73076. */
  73077. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73078. var material = subMesh.getMaterial();
  73079. if (material.disableDepthWrite) {
  73080. return false;
  73081. }
  73082. var defines = [];
  73083. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73084. var mesh = subMesh.getMesh();
  73085. // Alpha test
  73086. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73087. defines.push("#define ALPHATEST");
  73088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73089. attribs.push(BABYLON.VertexBuffer.UVKind);
  73090. defines.push("#define UV1");
  73091. }
  73092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73093. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73094. defines.push("#define UV2");
  73095. }
  73096. }
  73097. // Bones
  73098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73101. if (mesh.numBoneInfluencers > 4) {
  73102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73104. }
  73105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73106. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73107. }
  73108. else {
  73109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73110. }
  73111. // Instances
  73112. if (useInstances) {
  73113. defines.push("#define INSTANCES");
  73114. attribs.push("world0");
  73115. attribs.push("world1");
  73116. attribs.push("world2");
  73117. attribs.push("world3");
  73118. }
  73119. // Get correct effect
  73120. var join = defines.join("\n");
  73121. if (this._cachedDefines !== join) {
  73122. this._cachedDefines = join;
  73123. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73124. }
  73125. return this._effect.isReady();
  73126. };
  73127. /**
  73128. * Gets the texture which the depth map will be written to.
  73129. * @returns The depth map texture
  73130. */
  73131. DepthRenderer.prototype.getDepthMap = function () {
  73132. return this._depthMap;
  73133. };
  73134. /**
  73135. * Disposes of the depth renderer.
  73136. */
  73137. DepthRenderer.prototype.dispose = function () {
  73138. this._depthMap.dispose();
  73139. };
  73140. return DepthRenderer;
  73141. }());
  73142. BABYLON.DepthRenderer = DepthRenderer;
  73143. })(BABYLON || (BABYLON = {}));
  73144. //# sourceMappingURL=babylon.depthRenderer.js.map
  73145. var BABYLON;
  73146. (function (BABYLON) {
  73147. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73148. __extends(SSAORenderingPipeline, _super);
  73149. /**
  73150. * @constructor
  73151. * @param {string} name - The rendering pipeline name
  73152. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73153. * @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 }
  73154. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73155. */
  73156. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73157. var _this = _super.call(this, scene.getEngine(), name) || this;
  73158. // Members
  73159. /**
  73160. * The PassPostProcess id in the pipeline that contains the original scene color
  73161. */
  73162. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73163. /**
  73164. * The SSAO PostProcess id in the pipeline
  73165. */
  73166. _this.SSAORenderEffect = "SSAORenderEffect";
  73167. /**
  73168. * The horizontal blur PostProcess id in the pipeline
  73169. */
  73170. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73171. /**
  73172. * The vertical blur PostProcess id in the pipeline
  73173. */
  73174. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73175. /**
  73176. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73177. */
  73178. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73179. /**
  73180. * The output strength of the SSAO post-process. Default value is 1.0.
  73181. */
  73182. _this.totalStrength = 1.0;
  73183. /**
  73184. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73185. */
  73186. _this.radius = 0.0001;
  73187. /**
  73188. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73189. * Must not be equal to fallOff and superior to fallOff.
  73190. * Default value is 0.975
  73191. */
  73192. _this.area = 0.0075;
  73193. /**
  73194. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73195. * Must not be equal to area and inferior to area.
  73196. * Default value is 0.0
  73197. */
  73198. _this.fallOff = 0.000001;
  73199. /**
  73200. * The base color of the SSAO post-process
  73201. * The final result is "base + ssao" between [0, 1]
  73202. */
  73203. _this.base = 0.5;
  73204. _this._firstUpdate = true;
  73205. _this._scene = scene;
  73206. // Set up assets
  73207. _this._createRandomTexture();
  73208. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73209. var ssaoRatio = ratio.ssaoRatio || ratio;
  73210. var combineRatio = ratio.combineRatio || ratio;
  73211. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73212. _this._createSSAOPostProcess(ssaoRatio);
  73213. _this._createBlurPostProcess(ssaoRatio);
  73214. _this._createSSAOCombinePostProcess(combineRatio);
  73215. // Set up pipeline
  73216. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73217. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73218. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73219. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73220. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73221. // Finish
  73222. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73223. if (cameras)
  73224. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73225. return _this;
  73226. }
  73227. // Public Methods
  73228. /**
  73229. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73230. */
  73231. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73232. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73233. for (var i = 0; i < this._scene.cameras.length; i++) {
  73234. var camera = this._scene.cameras[i];
  73235. this._originalColorPostProcess.dispose(camera);
  73236. this._ssaoPostProcess.dispose(camera);
  73237. this._blurHPostProcess.dispose(camera);
  73238. this._blurVPostProcess.dispose(camera);
  73239. this._ssaoCombinePostProcess.dispose(camera);
  73240. }
  73241. this._randomTexture.dispose();
  73242. if (disableDepthRender)
  73243. this._scene.disableDepthRenderer();
  73244. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73245. _super.prototype.dispose.call(this);
  73246. };
  73247. // Private Methods
  73248. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73249. var _this = this;
  73250. var size = 16;
  73251. 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);
  73252. 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);
  73253. this._blurHPostProcess.onActivateObservable.add(function () {
  73254. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73255. _this._blurHPostProcess.kernel = size * dw;
  73256. });
  73257. this._blurVPostProcess.onActivateObservable.add(function () {
  73258. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73259. _this._blurVPostProcess.kernel = size * dw;
  73260. });
  73261. };
  73262. SSAORenderingPipeline.prototype._rebuild = function () {
  73263. this._firstUpdate = true;
  73264. _super.prototype._rebuild.call(this);
  73265. };
  73266. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73267. var _this = this;
  73268. var numSamples = 16;
  73269. var sampleSphere = [
  73270. 0.5381, 0.1856, -0.4319,
  73271. 0.1379, 0.2486, 0.4430,
  73272. 0.3371, 0.5679, -0.0057,
  73273. -0.6999, -0.0451, -0.0019,
  73274. 0.0689, -0.1598, -0.8547,
  73275. 0.0560, 0.0069, -0.1843,
  73276. -0.0146, 0.1402, 0.0762,
  73277. 0.0100, -0.1924, -0.0344,
  73278. -0.3577, -0.5301, -0.4358,
  73279. -0.3169, 0.1063, 0.0158,
  73280. 0.0103, -0.5869, 0.0046,
  73281. -0.0897, -0.4940, 0.3287,
  73282. 0.7119, -0.0154, -0.0918,
  73283. -0.0533, 0.0596, -0.5411,
  73284. 0.0352, -0.0631, 0.5460,
  73285. -0.4776, 0.2847, -0.0271
  73286. ];
  73287. var samplesFactor = 1.0 / numSamples;
  73288. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73289. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73290. "area", "fallOff", "base", "range", "viewport"
  73291. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73292. this._ssaoPostProcess.onApply = function (effect) {
  73293. if (_this._firstUpdate) {
  73294. effect.setArray3("sampleSphere", sampleSphere);
  73295. effect.setFloat("samplesFactor", samplesFactor);
  73296. effect.setFloat("randTextureTiles", 4.0);
  73297. }
  73298. effect.setFloat("totalStrength", _this.totalStrength);
  73299. effect.setFloat("radius", _this.radius);
  73300. effect.setFloat("area", _this.area);
  73301. effect.setFloat("fallOff", _this.fallOff);
  73302. effect.setFloat("base", _this.base);
  73303. effect.setTexture("textureSampler", _this._depthTexture);
  73304. effect.setTexture("randomSampler", _this._randomTexture);
  73305. };
  73306. };
  73307. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73308. var _this = this;
  73309. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73310. this._ssaoCombinePostProcess.onApply = function (effect) {
  73311. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73312. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73313. };
  73314. };
  73315. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73316. var size = 512;
  73317. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73318. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73319. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73320. var context = this._randomTexture.getContext();
  73321. var rand = function (min, max) {
  73322. return Math.random() * (max - min) + min;
  73323. };
  73324. var randVector = BABYLON.Vector3.Zero();
  73325. for (var x = 0; x < size; x++) {
  73326. for (var y = 0; y < size; y++) {
  73327. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73328. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73329. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73330. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73331. context.fillRect(x, y, 1, 1);
  73332. }
  73333. }
  73334. this._randomTexture.update(false);
  73335. };
  73336. __decorate([
  73337. BABYLON.serialize()
  73338. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73339. __decorate([
  73340. BABYLON.serialize()
  73341. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73342. __decorate([
  73343. BABYLON.serialize()
  73344. ], SSAORenderingPipeline.prototype, "area", void 0);
  73345. __decorate([
  73346. BABYLON.serialize()
  73347. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73348. __decorate([
  73349. BABYLON.serialize()
  73350. ], SSAORenderingPipeline.prototype, "base", void 0);
  73351. return SSAORenderingPipeline;
  73352. }(BABYLON.PostProcessRenderPipeline));
  73353. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73354. })(BABYLON || (BABYLON = {}));
  73355. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73356. var BABYLON;
  73357. (function (BABYLON) {
  73358. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73359. __extends(SSAO2RenderingPipeline, _super);
  73360. /**
  73361. * @constructor
  73362. * @param {string} name - The rendering pipeline name
  73363. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73364. * @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 }
  73365. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73366. */
  73367. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73368. var _this = _super.call(this, scene.getEngine(), name) || this;
  73369. // Members
  73370. /**
  73371. * The PassPostProcess id in the pipeline that contains the original scene color
  73372. */
  73373. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73374. /**
  73375. * The SSAO PostProcess id in the pipeline
  73376. */
  73377. _this.SSAORenderEffect = "SSAORenderEffect";
  73378. /**
  73379. * The horizontal blur PostProcess id in the pipeline
  73380. */
  73381. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73382. /**
  73383. * The vertical blur PostProcess id in the pipeline
  73384. */
  73385. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73386. /**
  73387. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73388. */
  73389. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73390. /**
  73391. * The output strength of the SSAO post-process. Default value is 1.0.
  73392. */
  73393. _this.totalStrength = 1.0;
  73394. /**
  73395. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73396. */
  73397. _this.maxZ = 100.0;
  73398. /**
  73399. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73400. */
  73401. _this.minZAspect = 0.2;
  73402. /**
  73403. * Number of samples used for the SSAO calculations. Default value is 8
  73404. */
  73405. _this._samples = 8;
  73406. /**
  73407. * Are we using bilateral blur ?
  73408. */
  73409. _this._expensiveBlur = true;
  73410. /**
  73411. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73412. */
  73413. _this.radius = 2.0;
  73414. /**
  73415. * The base color of the SSAO post-process
  73416. * The final result is "base + ssao" between [0, 1]
  73417. */
  73418. _this.base = 0.1;
  73419. _this._firstUpdate = true;
  73420. _this._scene = scene;
  73421. _this._ratio = ratio;
  73422. if (!_this.isSupported) {
  73423. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73424. return _this;
  73425. }
  73426. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73427. var blurRatio = _this._ratio.blurRatio || ratio;
  73428. // Set up assets
  73429. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73430. _this._createRandomTexture();
  73431. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73432. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73433. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73434. _this._createSSAOPostProcess(1.0);
  73435. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73436. _this._createSSAOCombinePostProcess(blurRatio);
  73437. // Set up pipeline
  73438. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73439. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73442. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73443. // Finish
  73444. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73445. if (cameras)
  73446. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73447. return _this;
  73448. }
  73449. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73450. get: function () {
  73451. return this._samples;
  73452. },
  73453. set: function (n) {
  73454. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73455. this._samples = n;
  73456. this._sampleSphere = this._generateHemisphere();
  73457. this._firstUpdate = true;
  73458. },
  73459. enumerable: true,
  73460. configurable: true
  73461. });
  73462. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73463. get: function () {
  73464. return this._expensiveBlur;
  73465. },
  73466. set: function (b) {
  73467. 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"]);
  73468. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73469. this._expensiveBlur = b;
  73470. this._firstUpdate = true;
  73471. },
  73472. enumerable: true,
  73473. configurable: true
  73474. });
  73475. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73476. /**
  73477. * Support test.
  73478. */
  73479. get: function () {
  73480. var engine = BABYLON.Engine.LastCreatedEngine;
  73481. if (!engine) {
  73482. return false;
  73483. }
  73484. return engine.getCaps().drawBuffersExtension;
  73485. },
  73486. enumerable: true,
  73487. configurable: true
  73488. });
  73489. // Public Methods
  73490. /**
  73491. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73492. */
  73493. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73494. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73495. for (var i = 0; i < this._scene.cameras.length; i++) {
  73496. var camera = this._scene.cameras[i];
  73497. this._originalColorPostProcess.dispose(camera);
  73498. this._ssaoPostProcess.dispose(camera);
  73499. this._blurHPostProcess.dispose(camera);
  73500. this._blurVPostProcess.dispose(camera);
  73501. this._ssaoCombinePostProcess.dispose(camera);
  73502. }
  73503. this._randomTexture.dispose();
  73504. if (disableGeometryBufferRenderer)
  73505. this._scene.disableGeometryBufferRenderer();
  73506. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73507. _super.prototype.dispose.call(this);
  73508. };
  73509. // Private Methods
  73510. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73511. var _this = this;
  73512. this._samplerOffsets = [];
  73513. var expensive = this.expensiveBlur;
  73514. for (var i = -8; i < 8; i++) {
  73515. this._samplerOffsets.push(i * 2 + 0.5);
  73516. }
  73517. 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");
  73518. this._blurHPostProcess.onApply = function (effect) {
  73519. if (!_this._scene.activeCamera) {
  73520. return;
  73521. }
  73522. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73523. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73524. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73525. effect.setFloat("radius", _this.radius);
  73526. effect.setTexture("depthSampler", _this._depthTexture);
  73527. if (_this._firstUpdate) {
  73528. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73529. }
  73530. };
  73531. 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");
  73532. this._blurVPostProcess.onApply = function (effect) {
  73533. if (!_this._scene.activeCamera) {
  73534. return;
  73535. }
  73536. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73537. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73538. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73539. effect.setFloat("radius", _this.radius);
  73540. effect.setTexture("depthSampler", _this._depthTexture);
  73541. if (_this._firstUpdate) {
  73542. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73543. _this._firstUpdate = false;
  73544. }
  73545. };
  73546. };
  73547. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73548. this._firstUpdate = true;
  73549. _super.prototype._rebuild.call(this);
  73550. };
  73551. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73552. var numSamples = this.samples;
  73553. var result = [];
  73554. var vector, scale;
  73555. var rand = function (min, max) {
  73556. return Math.random() * (max - min) + min;
  73557. };
  73558. var i = 0;
  73559. while (i < numSamples) {
  73560. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73561. vector.normalize();
  73562. scale = i / numSamples;
  73563. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73564. vector.scaleInPlace(scale);
  73565. result.push(vector.x, vector.y, vector.z);
  73566. i++;
  73567. }
  73568. return result;
  73569. };
  73570. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73571. var _this = this;
  73572. var numSamples = this.samples;
  73573. this._sampleSphere = this._generateHemisphere();
  73574. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73575. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73576. "base", "range", "projection", "near", "far", "texelSize",
  73577. "xViewport", "yViewport", "maxZ", "minZAspect"
  73578. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73579. this._ssaoPostProcess.onApply = function (effect) {
  73580. if (_this._firstUpdate) {
  73581. effect.setArray3("sampleSphere", _this._sampleSphere);
  73582. effect.setFloat("randTextureTiles", 4.0);
  73583. }
  73584. if (!_this._scene.activeCamera) {
  73585. return;
  73586. }
  73587. effect.setFloat("samplesFactor", 1 / _this.samples);
  73588. effect.setFloat("totalStrength", _this.totalStrength);
  73589. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73590. effect.setFloat("radius", _this.radius);
  73591. effect.setFloat("maxZ", _this.maxZ);
  73592. effect.setFloat("minZAspect", _this.minZAspect);
  73593. effect.setFloat("base", _this.base);
  73594. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73595. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73596. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73597. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73598. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73599. effect.setTexture("textureSampler", _this._depthTexture);
  73600. effect.setTexture("normalSampler", _this._normalTexture);
  73601. effect.setTexture("randomSampler", _this._randomTexture);
  73602. };
  73603. };
  73604. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73605. var _this = this;
  73606. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73607. this._ssaoCombinePostProcess.onApply = function (effect) {
  73608. var viewport = _this._scene.activeCamera.viewport;
  73609. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73610. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73611. };
  73612. };
  73613. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73614. var size = 512;
  73615. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73616. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73617. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73618. var context = this._randomTexture.getContext();
  73619. var rand = function (min, max) {
  73620. return Math.random() * (max - min) + min;
  73621. };
  73622. var randVector = BABYLON.Vector3.Zero();
  73623. for (var x = 0; x < size; x++) {
  73624. for (var y = 0; y < size; y++) {
  73625. randVector.x = rand(0.0, 1.0);
  73626. randVector.y = rand(0.0, 1.0);
  73627. randVector.z = 0.0;
  73628. randVector.normalize();
  73629. randVector.scaleInPlace(255);
  73630. randVector.x = Math.floor(randVector.x);
  73631. randVector.y = Math.floor(randVector.y);
  73632. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73633. context.fillRect(x, y, 1, 1);
  73634. }
  73635. }
  73636. this._randomTexture.update(false);
  73637. };
  73638. /**
  73639. * Serialize the rendering pipeline (Used when exporting)
  73640. * @returns the serialized object
  73641. */
  73642. SSAO2RenderingPipeline.prototype.serialize = function () {
  73643. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73644. serializationObject.customType = "SSAO2RenderingPipeline";
  73645. return serializationObject;
  73646. };
  73647. /**
  73648. * Parse the serialized pipeline
  73649. * @param source Source pipeline.
  73650. * @param scene The scene to load the pipeline to.
  73651. * @param rootUrl The URL of the serialized pipeline.
  73652. * @returns An instantiated pipeline from the serialized object.
  73653. */
  73654. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73655. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73656. };
  73657. __decorate([
  73658. BABYLON.serialize()
  73659. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73660. __decorate([
  73661. BABYLON.serialize()
  73662. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73663. __decorate([
  73664. BABYLON.serialize()
  73665. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73666. __decorate([
  73667. BABYLON.serialize("samples")
  73668. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73669. __decorate([
  73670. BABYLON.serialize()
  73671. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73672. __decorate([
  73673. BABYLON.serialize("expensiveBlur")
  73674. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73675. __decorate([
  73676. BABYLON.serialize()
  73677. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73678. __decorate([
  73679. BABYLON.serialize()
  73680. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73681. return SSAO2RenderingPipeline;
  73682. }(BABYLON.PostProcessRenderPipeline));
  73683. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73684. })(BABYLON || (BABYLON = {}));
  73685. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73686. // BABYLON.JS Chromatic Aberration GLSL Shader
  73687. // Author: Olivier Guyot
  73688. // Separates very slightly R, G and B colors on the edges of the screen
  73689. // Inspired by Francois Tarlier & Martins Upitis
  73690. var BABYLON;
  73691. (function (BABYLON) {
  73692. var LensRenderingPipeline = /** @class */ (function (_super) {
  73693. __extends(LensRenderingPipeline, _super);
  73694. /**
  73695. * @constructor
  73696. *
  73697. * Effect parameters are as follow:
  73698. * {
  73699. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73700. * edge_blur: number; // from 0 to x (1 for realism)
  73701. * distortion: number; // from 0 to x (1 for realism)
  73702. * grain_amount: number; // from 0 to 1
  73703. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73704. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73705. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73706. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73707. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73708. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73709. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73710. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73711. * }
  73712. * Note: if an effect parameter is unset, effect is disabled
  73713. *
  73714. * @param {string} name - The rendering pipeline name
  73715. * @param {object} parameters - An object containing all parameters (see above)
  73716. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73717. * @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)
  73718. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73719. */
  73720. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73721. if (ratio === void 0) { ratio = 1.0; }
  73722. var _this = _super.call(this, scene.getEngine(), name) || this;
  73723. // Lens effects can be of the following:
  73724. // - chromatic aberration (slight shift of RGB colors)
  73725. // - blur on the edge of the lens
  73726. // - lens distortion
  73727. // - depth-of-field blur & highlights enhancing
  73728. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73729. // - grain effect (noise or custom texture)
  73730. // Two additional texture samplers are needed:
  73731. // - depth map (for depth-of-field)
  73732. // - grain texture
  73733. /**
  73734. * The chromatic aberration PostProcess id in the pipeline
  73735. */
  73736. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73737. /**
  73738. * The highlights enhancing PostProcess id in the pipeline
  73739. */
  73740. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73741. /**
  73742. * The depth-of-field PostProcess id in the pipeline
  73743. */
  73744. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73745. _this._scene = scene;
  73746. // Fetch texture samplers
  73747. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73748. if (parameters.grain_texture) {
  73749. _this._grainTexture = parameters.grain_texture;
  73750. }
  73751. else {
  73752. _this._createGrainTexture();
  73753. }
  73754. // save parameters
  73755. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73756. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73757. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73758. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73759. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73760. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73761. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73762. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73763. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73764. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73765. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73766. // Create effects
  73767. _this._createChromaticAberrationPostProcess(ratio);
  73768. _this._createHighlightsPostProcess(ratio);
  73769. _this._createDepthOfFieldPostProcess(ratio / 4);
  73770. // Set up pipeline
  73771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73772. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73774. if (_this._highlightsGain === -1) {
  73775. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73776. }
  73777. // Finish
  73778. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73779. if (cameras) {
  73780. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73781. }
  73782. return _this;
  73783. }
  73784. // public methods (self explanatory)
  73785. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73786. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73787. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73788. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73789. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73790. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73791. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73792. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73793. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73794. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73795. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73796. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73797. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73798. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73799. };
  73800. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73801. this._highlightsPostProcess.updateEffect();
  73802. };
  73803. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73804. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73805. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73806. this._highlightsGain = amount;
  73807. };
  73808. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73809. if (this._highlightsGain === -1) {
  73810. this._highlightsGain = 1.0;
  73811. }
  73812. this._highlightsThreshold = amount;
  73813. };
  73814. LensRenderingPipeline.prototype.disableHighlights = function () {
  73815. this._highlightsGain = -1;
  73816. };
  73817. /**
  73818. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73819. */
  73820. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73821. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73822. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73823. this._chromaticAberrationPostProcess = null;
  73824. this._highlightsPostProcess = null;
  73825. this._depthOfFieldPostProcess = null;
  73826. this._grainTexture.dispose();
  73827. if (disableDepthRender)
  73828. this._scene.disableDepthRenderer();
  73829. };
  73830. // colors shifting and distortion
  73831. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73832. var _this = this;
  73833. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73834. [], // samplers
  73835. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73836. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73837. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73838. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73839. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73840. effect.setFloat('radialIntensity', 1);
  73841. effect.setFloat2('direction', 17, 17);
  73842. effect.setFloat2('centerPosition', 0.5, 0.5);
  73843. };
  73844. };
  73845. // highlights enhancing
  73846. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73847. var _this = this;
  73848. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73849. [], // samplers
  73850. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73851. this._highlightsPostProcess.onApply = function (effect) {
  73852. effect.setFloat('gain', _this._highlightsGain);
  73853. effect.setFloat('threshold', _this._highlightsThreshold);
  73854. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73855. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73856. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73857. };
  73858. };
  73859. // colors shifting and distortion
  73860. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73861. var _this = this;
  73862. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73863. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73864. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73865. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73866. this._depthOfFieldPostProcess.onApply = function (effect) {
  73867. effect.setTexture("depthSampler", _this._depthTexture);
  73868. effect.setTexture("grainSampler", _this._grainTexture);
  73869. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73870. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73871. effect.setFloat('grain_amount', _this._grainAmount);
  73872. effect.setBool('blur_noise', _this._blurNoise);
  73873. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73874. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73875. effect.setFloat('distortion', _this._distortion);
  73876. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73877. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73878. effect.setFloat('aperture', _this._dofAperture);
  73879. effect.setFloat('darken', _this._dofDarken);
  73880. effect.setFloat('edge_blur', _this._edgeBlur);
  73881. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73882. if (_this._scene.activeCamera) {
  73883. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73884. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73885. }
  73886. };
  73887. };
  73888. // creates a black and white random noise texture, 512x512
  73889. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73890. var size = 512;
  73891. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73892. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73893. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73894. var context = this._grainTexture.getContext();
  73895. var rand = function (min, max) {
  73896. return Math.random() * (max - min) + min;
  73897. };
  73898. var value;
  73899. for (var x = 0; x < size; x++) {
  73900. for (var y = 0; y < size; y++) {
  73901. value = Math.floor(rand(0.42, 0.58) * 255);
  73902. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73903. context.fillRect(x, y, 1, 1);
  73904. }
  73905. }
  73906. this._grainTexture.update(false);
  73907. };
  73908. return LensRenderingPipeline;
  73909. }(BABYLON.PostProcessRenderPipeline));
  73910. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73911. })(BABYLON || (BABYLON = {}));
  73912. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73913. var BABYLON;
  73914. (function (BABYLON) {
  73915. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73916. __extends(StandardRenderingPipeline, _super);
  73917. /**
  73918. * @constructor
  73919. * @param {string} name - The rendering pipeline name
  73920. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73921. * @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)
  73922. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73923. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73924. */
  73925. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73926. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73927. var _this = _super.call(this, scene.getEngine(), name) || this;
  73928. _this.downSampleX4PostProcess = null;
  73929. _this.brightPassPostProcess = null;
  73930. _this.blurHPostProcesses = [];
  73931. _this.blurVPostProcesses = [];
  73932. _this.textureAdderPostProcess = null;
  73933. _this.volumetricLightPostProcess = null;
  73934. _this.volumetricLightSmoothXPostProcess = null;
  73935. _this.volumetricLightSmoothYPostProcess = null;
  73936. _this.volumetricLightMergePostProces = null;
  73937. _this.volumetricLightFinalPostProcess = null;
  73938. _this.luminancePostProcess = null;
  73939. _this.luminanceDownSamplePostProcesses = [];
  73940. _this.hdrPostProcess = null;
  73941. _this.textureAdderFinalPostProcess = null;
  73942. _this.lensFlareFinalPostProcess = null;
  73943. _this.hdrFinalPostProcess = null;
  73944. _this.lensFlarePostProcess = null;
  73945. _this.lensFlareComposePostProcess = null;
  73946. _this.motionBlurPostProcess = null;
  73947. _this.depthOfFieldPostProcess = null;
  73948. // Values
  73949. _this.brightThreshold = 1.0;
  73950. _this.blurWidth = 512.0;
  73951. _this.horizontalBlur = false;
  73952. _this.exposure = 1.0;
  73953. _this.lensTexture = null;
  73954. _this.volumetricLightCoefficient = 0.2;
  73955. _this.volumetricLightPower = 4.0;
  73956. _this.volumetricLightBlurScale = 64.0;
  73957. _this.sourceLight = null;
  73958. _this.hdrMinimumLuminance = 1.0;
  73959. _this.hdrDecreaseRate = 0.5;
  73960. _this.hdrIncreaseRate = 0.5;
  73961. _this.lensColorTexture = null;
  73962. _this.lensFlareStrength = 20.0;
  73963. _this.lensFlareGhostDispersal = 1.4;
  73964. _this.lensFlareHaloWidth = 0.7;
  73965. _this.lensFlareDistortionStrength = 16.0;
  73966. _this.lensStarTexture = null;
  73967. _this.lensFlareDirtTexture = null;
  73968. _this.depthOfFieldDistance = 10.0;
  73969. _this.depthOfFieldBlurWidth = 64.0;
  73970. _this.motionStrength = 1.0;
  73971. // IAnimatable
  73972. _this.animations = [];
  73973. _this._currentDepthOfFieldSource = null;
  73974. _this._hdrCurrentLuminance = 1.0;
  73975. // Getters and setters
  73976. _this._bloomEnabled = true;
  73977. _this._depthOfFieldEnabled = false;
  73978. _this._vlsEnabled = false;
  73979. _this._lensFlareEnabled = false;
  73980. _this._hdrEnabled = false;
  73981. _this._motionBlurEnabled = false;
  73982. _this._motionBlurSamples = 64.0;
  73983. _this._volumetricLightStepsCount = 50.0;
  73984. _this._cameras = cameras || [];
  73985. // Initialize
  73986. _this._scene = scene;
  73987. _this._basePostProcess = originalPostProcess;
  73988. _this._ratio = ratio;
  73989. // Misc
  73990. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73991. // Finish
  73992. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73993. _this._buildPipeline();
  73994. return _this;
  73995. }
  73996. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73997. get: function () {
  73998. return this._bloomEnabled;
  73999. },
  74000. set: function (enabled) {
  74001. if (this._bloomEnabled === enabled) {
  74002. return;
  74003. }
  74004. this._bloomEnabled = enabled;
  74005. this._buildPipeline();
  74006. },
  74007. enumerable: true,
  74008. configurable: true
  74009. });
  74010. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74011. get: function () {
  74012. return this._depthOfFieldEnabled;
  74013. },
  74014. set: function (enabled) {
  74015. if (this._depthOfFieldEnabled === enabled) {
  74016. return;
  74017. }
  74018. this._depthOfFieldEnabled = enabled;
  74019. this._buildPipeline();
  74020. },
  74021. enumerable: true,
  74022. configurable: true
  74023. });
  74024. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74025. get: function () {
  74026. return this._lensFlareEnabled;
  74027. },
  74028. set: function (enabled) {
  74029. if (this._lensFlareEnabled === enabled) {
  74030. return;
  74031. }
  74032. this._lensFlareEnabled = enabled;
  74033. this._buildPipeline();
  74034. },
  74035. enumerable: true,
  74036. configurable: true
  74037. });
  74038. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74039. get: function () {
  74040. return this._hdrEnabled;
  74041. },
  74042. set: function (enabled) {
  74043. if (this._hdrEnabled === enabled) {
  74044. return;
  74045. }
  74046. this._hdrEnabled = enabled;
  74047. this._buildPipeline();
  74048. },
  74049. enumerable: true,
  74050. configurable: true
  74051. });
  74052. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74053. get: function () {
  74054. return this._vlsEnabled;
  74055. },
  74056. set: function (enabled) {
  74057. if (this._vlsEnabled === enabled) {
  74058. return;
  74059. }
  74060. if (enabled) {
  74061. var geometry = this._scene.enableGeometryBufferRenderer();
  74062. if (!geometry) {
  74063. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74064. return;
  74065. }
  74066. }
  74067. this._vlsEnabled = enabled;
  74068. this._buildPipeline();
  74069. },
  74070. enumerable: true,
  74071. configurable: true
  74072. });
  74073. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74074. get: function () {
  74075. return this._motionBlurEnabled;
  74076. },
  74077. set: function (enabled) {
  74078. if (this._motionBlurEnabled === enabled) {
  74079. return;
  74080. }
  74081. this._motionBlurEnabled = enabled;
  74082. this._buildPipeline();
  74083. },
  74084. enumerable: true,
  74085. configurable: true
  74086. });
  74087. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74088. get: function () {
  74089. return this._volumetricLightStepsCount;
  74090. },
  74091. set: function (count) {
  74092. if (this.volumetricLightPostProcess) {
  74093. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74094. }
  74095. this._volumetricLightStepsCount = count;
  74096. },
  74097. enumerable: true,
  74098. configurable: true
  74099. });
  74100. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74101. get: function () {
  74102. return this._motionBlurSamples;
  74103. },
  74104. set: function (samples) {
  74105. if (this.motionBlurPostProcess) {
  74106. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74107. }
  74108. this._motionBlurSamples = samples;
  74109. },
  74110. enumerable: true,
  74111. configurable: true
  74112. });
  74113. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74114. var _this = this;
  74115. var ratio = this._ratio;
  74116. var scene = this._scene;
  74117. this._disposePostProcesses();
  74118. this._reset();
  74119. // Create pass post-process
  74120. if (!this._basePostProcess) {
  74121. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74122. this.originalPostProcess.onApply = function (effect) {
  74123. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74124. };
  74125. }
  74126. else {
  74127. this.originalPostProcess = this._basePostProcess;
  74128. }
  74129. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74130. this._currentDepthOfFieldSource = this.originalPostProcess;
  74131. if (this._bloomEnabled) {
  74132. // Create down sample X4 post-process
  74133. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74134. // Create bright pass post-process
  74135. this._createBrightPassPostProcess(scene, ratio / 2);
  74136. // Create gaussian blur post-processes (down sampling blurs)
  74137. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74138. // Create texture adder post-process
  74139. this._createTextureAdderPostProcess(scene, ratio);
  74140. // Create depth-of-field source post-process
  74141. 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);
  74142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74143. }
  74144. if (this._vlsEnabled) {
  74145. // Create volumetric light
  74146. this._createVolumetricLightPostProcess(scene, ratio);
  74147. // Create volumetric light final post-process
  74148. 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);
  74149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74150. }
  74151. if (this._lensFlareEnabled) {
  74152. // Create lens flare post-process
  74153. this._createLensFlarePostProcess(scene, ratio);
  74154. // Create depth-of-field source post-process post lens-flare and disable it now
  74155. 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);
  74156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74157. }
  74158. if (this._hdrEnabled) {
  74159. // Create luminance
  74160. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74161. // Create HDR
  74162. this._createHdrPostProcess(scene, ratio);
  74163. // Create depth-of-field source post-process post hdr and disable it now
  74164. 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);
  74165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74166. }
  74167. if (this._depthOfFieldEnabled) {
  74168. // Create gaussian blur used by depth-of-field
  74169. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74170. // Create depth-of-field post-process
  74171. this._createDepthOfFieldPostProcess(scene, ratio);
  74172. }
  74173. if (this._motionBlurEnabled) {
  74174. // Create motion blur post-process
  74175. this._createMotionBlurPostProcess(scene, ratio);
  74176. }
  74177. if (this._cameras !== null) {
  74178. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74179. }
  74180. };
  74181. // Down Sample X4 Post-Processs
  74182. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74183. var _this = this;
  74184. var downSampleX4Offsets = new Array(32);
  74185. 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);
  74186. this.downSampleX4PostProcess.onApply = function (effect) {
  74187. var id = 0;
  74188. var width = _this.downSampleX4PostProcess.width;
  74189. var height = _this.downSampleX4PostProcess.height;
  74190. for (var i = -2; i < 2; i++) {
  74191. for (var j = -2; j < 2; j++) {
  74192. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74193. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74194. id += 2;
  74195. }
  74196. }
  74197. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74198. };
  74199. // Add to pipeline
  74200. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74201. };
  74202. // Brightpass Post-Process
  74203. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74204. var _this = this;
  74205. var brightOffsets = new Array(8);
  74206. 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);
  74207. this.brightPassPostProcess.onApply = function (effect) {
  74208. var sU = (1.0 / _this.brightPassPostProcess.width);
  74209. var sV = (1.0 / _this.brightPassPostProcess.height);
  74210. brightOffsets[0] = -0.5 * sU;
  74211. brightOffsets[1] = 0.5 * sV;
  74212. brightOffsets[2] = 0.5 * sU;
  74213. brightOffsets[3] = 0.5 * sV;
  74214. brightOffsets[4] = -0.5 * sU;
  74215. brightOffsets[5] = -0.5 * sV;
  74216. brightOffsets[6] = 0.5 * sU;
  74217. brightOffsets[7] = -0.5 * sV;
  74218. effect.setArray2("dsOffsets", brightOffsets);
  74219. effect.setFloat("brightThreshold", _this.brightThreshold);
  74220. };
  74221. // Add to pipeline
  74222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74223. };
  74224. // Create blur H&V post-processes
  74225. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74226. var _this = this;
  74227. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74228. var engine = scene.getEngine();
  74229. 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);
  74230. 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);
  74231. blurX.onActivateObservable.add(function () {
  74232. var dw = blurX.width / engine.getRenderWidth();
  74233. blurX.kernel = _this[blurWidthKey] * dw;
  74234. });
  74235. blurY.onActivateObservable.add(function () {
  74236. var dw = blurY.height / engine.getRenderHeight();
  74237. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74238. });
  74239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74241. this.blurHPostProcesses.push(blurX);
  74242. this.blurVPostProcesses.push(blurY);
  74243. };
  74244. // Create texture adder post-process
  74245. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74246. var _this = this;
  74247. 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);
  74248. this.textureAdderPostProcess.onApply = function (effect) {
  74249. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74250. effect.setTexture("lensSampler", _this.lensTexture);
  74251. effect.setFloat("exposure", _this.exposure);
  74252. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74253. };
  74254. // Add to pipeline
  74255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74256. };
  74257. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74258. var _this = this;
  74259. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74260. geometryRenderer.enablePosition = true;
  74261. var geometry = geometryRenderer.getGBuffer();
  74262. // Base post-process
  74263. 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));
  74264. var depthValues = BABYLON.Vector2.Zero();
  74265. this.volumetricLightPostProcess.onApply = function (effect) {
  74266. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74267. var generator = _this.sourceLight.getShadowGenerator();
  74268. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74269. effect.setTexture("positionSampler", geometry.textures[2]);
  74270. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74271. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74272. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74273. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74274. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74275. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74276. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74277. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74278. effect.setVector2("depthValues", depthValues);
  74279. }
  74280. };
  74281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74282. // Smooth
  74283. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74284. // Merge
  74285. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74286. this.volumetricLightMergePostProces.onApply = function (effect) {
  74287. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74288. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74289. };
  74290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74291. };
  74292. // Create luminance
  74293. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74294. var _this = this;
  74295. // Create luminance
  74296. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74297. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74298. var offsets = [];
  74299. this.luminancePostProcess.onApply = function (effect) {
  74300. var sU = (1.0 / _this.luminancePostProcess.width);
  74301. var sV = (1.0 / _this.luminancePostProcess.height);
  74302. offsets[0] = -0.5 * sU;
  74303. offsets[1] = 0.5 * sV;
  74304. offsets[2] = 0.5 * sU;
  74305. offsets[3] = 0.5 * sV;
  74306. offsets[4] = -0.5 * sU;
  74307. offsets[5] = -0.5 * sV;
  74308. offsets[6] = 0.5 * sU;
  74309. offsets[7] = -0.5 * sV;
  74310. effect.setArray2("lumOffsets", offsets);
  74311. };
  74312. // Add to pipeline
  74313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74314. // Create down sample luminance
  74315. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74316. var size = Math.pow(3, i);
  74317. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74318. if (i === 0) {
  74319. defines += "#define FINAL_DOWN_SAMPLER";
  74320. }
  74321. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74322. this.luminanceDownSamplePostProcesses.push(postProcess);
  74323. }
  74324. // Create callbacks and add effects
  74325. var lastLuminance = this.luminancePostProcess;
  74326. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74327. var downSampleOffsets = new Array(18);
  74328. pp.onApply = function (effect) {
  74329. if (!lastLuminance) {
  74330. return;
  74331. }
  74332. var id = 0;
  74333. for (var x = -1; x < 2; x++) {
  74334. for (var y = -1; y < 2; y++) {
  74335. downSampleOffsets[id] = x / lastLuminance.width;
  74336. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74337. id += 2;
  74338. }
  74339. }
  74340. effect.setArray2("dsOffsets", downSampleOffsets);
  74341. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74342. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74343. lastLuminance = _this.luminancePostProcess;
  74344. }
  74345. else {
  74346. lastLuminance = pp;
  74347. }
  74348. };
  74349. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74350. pp.onAfterRender = function (effect) {
  74351. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74352. 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);
  74353. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74354. };
  74355. }
  74356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74357. });
  74358. };
  74359. // Create HDR post-process
  74360. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74361. var _this = this;
  74362. 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);
  74363. var outputLiminance = 1;
  74364. var time = 0;
  74365. var lastTime = 0;
  74366. this.hdrPostProcess.onApply = function (effect) {
  74367. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74368. time += scene.getEngine().getDeltaTime();
  74369. if (outputLiminance < 0) {
  74370. outputLiminance = _this._hdrCurrentLuminance;
  74371. }
  74372. else {
  74373. var dt = (lastTime - time) / 1000.0;
  74374. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74375. outputLiminance += _this.hdrDecreaseRate * dt;
  74376. }
  74377. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74378. outputLiminance -= _this.hdrIncreaseRate * dt;
  74379. }
  74380. else {
  74381. outputLiminance = _this._hdrCurrentLuminance;
  74382. }
  74383. }
  74384. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74385. effect.setFloat("averageLuminance", outputLiminance);
  74386. lastTime = time;
  74387. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74388. };
  74389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74390. };
  74391. // Create lens flare post-process
  74392. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74393. var _this = this;
  74394. 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);
  74395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74396. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74397. 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);
  74398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74399. var resolution = new BABYLON.Vector2(0, 0);
  74400. // Lens flare
  74401. this.lensFlarePostProcess.onApply = function (effect) {
  74402. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74403. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74404. effect.setFloat("strength", _this.lensFlareStrength);
  74405. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74406. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74407. // Shift
  74408. resolution.x = _this.lensFlarePostProcess.width;
  74409. resolution.y = _this.lensFlarePostProcess.height;
  74410. effect.setVector2("resolution", resolution);
  74411. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74412. };
  74413. // Compose
  74414. 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);
  74415. 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);
  74416. this.lensFlareComposePostProcess.onApply = function (effect) {
  74417. if (!_this._scene.activeCamera) {
  74418. return;
  74419. }
  74420. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74421. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74422. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74423. // Lens start rotation matrix
  74424. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74425. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74426. 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));
  74427. camRot *= 4.0;
  74428. 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);
  74429. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74430. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74431. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74432. };
  74433. };
  74434. // Create depth-of-field post-process
  74435. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74436. var _this = this;
  74437. 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);
  74438. this.depthOfFieldPostProcess.onApply = function (effect) {
  74439. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74440. effect.setTexture("depthSampler", _this._getDepthTexture());
  74441. effect.setFloat("distance", _this.depthOfFieldDistance);
  74442. };
  74443. // Add to pipeline
  74444. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74445. };
  74446. // Create motion blur post-process
  74447. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74448. var _this = this;
  74449. 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);
  74450. var motionScale = 0;
  74451. var prevViewProjection = BABYLON.Matrix.Identity();
  74452. var invViewProjection = BABYLON.Matrix.Identity();
  74453. var viewProjection = BABYLON.Matrix.Identity();
  74454. var screenSize = BABYLON.Vector2.Zero();
  74455. this.motionBlurPostProcess.onApply = function (effect) {
  74456. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74457. viewProjection.invertToRef(invViewProjection);
  74458. effect.setMatrix("inverseViewProjection", invViewProjection);
  74459. effect.setMatrix("prevViewProjection", prevViewProjection);
  74460. prevViewProjection = viewProjection;
  74461. screenSize.x = _this.motionBlurPostProcess.width;
  74462. screenSize.y = _this.motionBlurPostProcess.height;
  74463. effect.setVector2("screenSize", screenSize);
  74464. motionScale = scene.getEngine().getFps() / 60.0;
  74465. effect.setFloat("motionScale", motionScale);
  74466. effect.setFloat("motionStrength", _this.motionStrength);
  74467. effect.setTexture("depthSampler", _this._getDepthTexture());
  74468. };
  74469. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74470. };
  74471. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74472. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74473. var renderer = this._scene.enableGeometryBufferRenderer();
  74474. return renderer.getGBuffer().textures[0];
  74475. }
  74476. return this._scene.enableDepthRenderer().getDepthMap();
  74477. };
  74478. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74479. for (var i = 0; i < this._cameras.length; i++) {
  74480. var camera = this._cameras[i];
  74481. if (this.originalPostProcess) {
  74482. this.originalPostProcess.dispose(camera);
  74483. }
  74484. if (this.downSampleX4PostProcess) {
  74485. this.downSampleX4PostProcess.dispose(camera);
  74486. }
  74487. if (this.brightPassPostProcess) {
  74488. this.brightPassPostProcess.dispose(camera);
  74489. }
  74490. if (this.textureAdderPostProcess) {
  74491. this.textureAdderPostProcess.dispose(camera);
  74492. }
  74493. if (this.textureAdderFinalPostProcess) {
  74494. this.textureAdderFinalPostProcess.dispose(camera);
  74495. }
  74496. if (this.volumetricLightPostProcess) {
  74497. this.volumetricLightPostProcess.dispose(camera);
  74498. }
  74499. if (this.volumetricLightSmoothXPostProcess) {
  74500. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74501. }
  74502. if (this.volumetricLightSmoothYPostProcess) {
  74503. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74504. }
  74505. if (this.volumetricLightMergePostProces) {
  74506. this.volumetricLightMergePostProces.dispose(camera);
  74507. }
  74508. if (this.volumetricLightFinalPostProcess) {
  74509. this.volumetricLightFinalPostProcess.dispose(camera);
  74510. }
  74511. if (this.lensFlarePostProcess) {
  74512. this.lensFlarePostProcess.dispose(camera);
  74513. }
  74514. if (this.lensFlareComposePostProcess) {
  74515. this.lensFlareComposePostProcess.dispose(camera);
  74516. }
  74517. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74518. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74519. }
  74520. if (this.luminancePostProcess) {
  74521. this.luminancePostProcess.dispose(camera);
  74522. }
  74523. if (this.hdrPostProcess) {
  74524. this.hdrPostProcess.dispose(camera);
  74525. }
  74526. if (this.hdrFinalPostProcess) {
  74527. this.hdrFinalPostProcess.dispose(camera);
  74528. }
  74529. if (this.depthOfFieldPostProcess) {
  74530. this.depthOfFieldPostProcess.dispose(camera);
  74531. }
  74532. if (this.motionBlurPostProcess) {
  74533. this.motionBlurPostProcess.dispose(camera);
  74534. }
  74535. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74536. this.blurHPostProcesses[j].dispose(camera);
  74537. }
  74538. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74539. this.blurVPostProcesses[j].dispose(camera);
  74540. }
  74541. }
  74542. this.originalPostProcess = null;
  74543. this.downSampleX4PostProcess = null;
  74544. this.brightPassPostProcess = null;
  74545. this.textureAdderPostProcess = null;
  74546. this.textureAdderFinalPostProcess = null;
  74547. this.volumetricLightPostProcess = null;
  74548. this.volumetricLightSmoothXPostProcess = null;
  74549. this.volumetricLightSmoothYPostProcess = null;
  74550. this.volumetricLightMergePostProces = null;
  74551. this.volumetricLightFinalPostProcess = null;
  74552. this.lensFlarePostProcess = null;
  74553. this.lensFlareComposePostProcess = null;
  74554. this.luminancePostProcess = null;
  74555. this.hdrPostProcess = null;
  74556. this.hdrFinalPostProcess = null;
  74557. this.depthOfFieldPostProcess = null;
  74558. this.motionBlurPostProcess = null;
  74559. this.luminanceDownSamplePostProcesses = [];
  74560. this.blurHPostProcesses = [];
  74561. this.blurVPostProcesses = [];
  74562. };
  74563. /**
  74564. * Dispose of the pipeline and stop all post processes
  74565. */
  74566. StandardRenderingPipeline.prototype.dispose = function () {
  74567. this._disposePostProcesses();
  74568. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74569. _super.prototype.dispose.call(this);
  74570. };
  74571. /**
  74572. * Serialize the rendering pipeline (Used when exporting)
  74573. * @returns the serialized object
  74574. */
  74575. StandardRenderingPipeline.prototype.serialize = function () {
  74576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74577. if (this.sourceLight) {
  74578. serializationObject.sourceLightId = this.sourceLight.id;
  74579. }
  74580. serializationObject.customType = "StandardRenderingPipeline";
  74581. return serializationObject;
  74582. };
  74583. /**
  74584. * Parse the serialized pipeline
  74585. * @param source Source pipeline.
  74586. * @param scene The scene to load the pipeline to.
  74587. * @param rootUrl The URL of the serialized pipeline.
  74588. * @returns An instantiated pipeline from the serialized object.
  74589. */
  74590. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74591. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74592. if (source.sourceLightId) {
  74593. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74594. }
  74595. return p;
  74596. };
  74597. // Luminance steps
  74598. StandardRenderingPipeline.LuminanceSteps = 6;
  74599. __decorate([
  74600. BABYLON.serialize()
  74601. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74602. __decorate([
  74603. BABYLON.serialize()
  74604. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74605. __decorate([
  74606. BABYLON.serialize()
  74607. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74608. __decorate([
  74609. BABYLON.serialize()
  74610. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74611. __decorate([
  74612. BABYLON.serializeAsTexture("lensTexture")
  74613. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74614. __decorate([
  74615. BABYLON.serialize()
  74616. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74617. __decorate([
  74618. BABYLON.serialize()
  74619. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74620. __decorate([
  74621. BABYLON.serialize()
  74622. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74623. __decorate([
  74624. BABYLON.serialize()
  74625. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74626. __decorate([
  74627. BABYLON.serialize()
  74628. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74629. __decorate([
  74630. BABYLON.serialize()
  74631. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74632. __decorate([
  74633. BABYLON.serializeAsTexture("lensColorTexture")
  74634. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74635. __decorate([
  74636. BABYLON.serialize()
  74637. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74638. __decorate([
  74639. BABYLON.serialize()
  74640. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74641. __decorate([
  74642. BABYLON.serialize()
  74643. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74644. __decorate([
  74645. BABYLON.serialize()
  74646. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74647. __decorate([
  74648. BABYLON.serializeAsTexture("lensStarTexture")
  74649. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74650. __decorate([
  74651. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74652. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74653. __decorate([
  74654. BABYLON.serialize()
  74655. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74656. __decorate([
  74657. BABYLON.serialize()
  74658. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74659. __decorate([
  74660. BABYLON.serialize()
  74661. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74662. __decorate([
  74663. BABYLON.serialize()
  74664. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74665. __decorate([
  74666. BABYLON.serialize()
  74667. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74668. __decorate([
  74669. BABYLON.serialize()
  74670. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74671. __decorate([
  74672. BABYLON.serialize()
  74673. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74674. __decorate([
  74675. BABYLON.serialize()
  74676. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74677. __decorate([
  74678. BABYLON.serialize()
  74679. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74680. __decorate([
  74681. BABYLON.serialize()
  74682. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74683. __decorate([
  74684. BABYLON.serialize()
  74685. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74686. __decorate([
  74687. BABYLON.serialize()
  74688. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74689. return StandardRenderingPipeline;
  74690. }(BABYLON.PostProcessRenderPipeline));
  74691. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74692. })(BABYLON || (BABYLON = {}));
  74693. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74694. var BABYLON;
  74695. (function (BABYLON) {
  74696. var FxaaPostProcess = /** @class */ (function (_super) {
  74697. __extends(FxaaPostProcess, _super);
  74698. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74699. if (camera === void 0) { camera = null; }
  74700. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74701. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74702. var defines = _this._getDefines();
  74703. _this.updateEffect(defines);
  74704. _this.onApplyObservable.add(function (effect) {
  74705. var texelSize = _this.texelSize;
  74706. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74707. });
  74708. return _this;
  74709. }
  74710. FxaaPostProcess.prototype._getDefines = function () {
  74711. var engine = this.getEngine();
  74712. if (!engine) {
  74713. return null;
  74714. }
  74715. var glInfo = engine.getGlInfo();
  74716. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74717. return "#define MALI 1\n";
  74718. }
  74719. return null;
  74720. };
  74721. return FxaaPostProcess;
  74722. }(BABYLON.PostProcess));
  74723. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74724. })(BABYLON || (BABYLON = {}));
  74725. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74726. var BABYLON;
  74727. (function (BABYLON) {
  74728. /**
  74729. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74730. */
  74731. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74732. __extends(ChromaticAberrationPostProcess, _super);
  74733. /**
  74734. * Creates a new instance ChromaticAberrationPostProcess
  74735. * @param name The name of the effect.
  74736. * @param screenWidth The width of the screen to apply the effect on.
  74737. * @param screenHeight The height of the screen to apply the effect on.
  74738. * @param options The required width/height ratio to downsize to before computing the render pass.
  74739. * @param camera The camera to apply the render pass to.
  74740. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74741. * @param engine The engine which the post process will be applied. (default: current engine)
  74742. * @param reusable If the post process can be reused on the same frame. (default: false)
  74743. * @param textureType Type of textures used when performing the post process. (default: 0)
  74744. * @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)
  74745. */
  74746. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74747. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74748. if (blockCompilation === void 0) { blockCompilation = false; }
  74749. 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;
  74750. /**
  74751. * The amount of seperation of rgb channels (default: 30)
  74752. */
  74753. _this.aberrationAmount = 30;
  74754. /**
  74755. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74756. */
  74757. _this.radialIntensity = 0;
  74758. /**
  74759. * 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))
  74760. */
  74761. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74762. /**
  74763. * 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))
  74764. */
  74765. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74766. _this.onApplyObservable.add(function (effect) {
  74767. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74768. effect.setFloat('screen_width', screenWidth);
  74769. effect.setFloat('screen_height', screenHeight);
  74770. effect.setFloat('radialIntensity', _this.radialIntensity);
  74771. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74772. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74773. });
  74774. return _this;
  74775. }
  74776. return ChromaticAberrationPostProcess;
  74777. }(BABYLON.PostProcess));
  74778. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74779. })(BABYLON || (BABYLON = {}));
  74780. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74781. var BABYLON;
  74782. (function (BABYLON) {
  74783. /**
  74784. * The GrainPostProcess adds noise to the image at mid luminance levels
  74785. */
  74786. var GrainPostProcess = /** @class */ (function (_super) {
  74787. __extends(GrainPostProcess, _super);
  74788. /**
  74789. * Creates a new instance of @see GrainPostProcess
  74790. * @param name The name of the effect.
  74791. * @param options The required width/height ratio to downsize to before computing the render pass.
  74792. * @param camera The camera to apply the render pass to.
  74793. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74794. * @param engine The engine which the post process will be applied. (default: current engine)
  74795. * @param reusable If the post process can be reused on the same frame. (default: false)
  74796. * @param textureType Type of textures used when performing the post process. (default: 0)
  74797. * @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)
  74798. */
  74799. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74800. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74801. if (blockCompilation === void 0) { blockCompilation = false; }
  74802. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74803. /**
  74804. * The intensity of the grain added (default: 30)
  74805. */
  74806. _this.intensity = 30;
  74807. /**
  74808. * If the grain should be randomized on every frame
  74809. */
  74810. _this.animated = false;
  74811. _this.onApplyObservable.add(function (effect) {
  74812. effect.setFloat('intensity', _this.intensity);
  74813. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74814. });
  74815. return _this;
  74816. }
  74817. return GrainPostProcess;
  74818. }(BABYLON.PostProcess));
  74819. BABYLON.GrainPostProcess = GrainPostProcess;
  74820. })(BABYLON || (BABYLON = {}));
  74821. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74822. var BABYLON;
  74823. (function (BABYLON) {
  74824. /**
  74825. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74826. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74827. */
  74828. var SharpenPostProcess = /** @class */ (function (_super) {
  74829. __extends(SharpenPostProcess, _super);
  74830. /**
  74831. * Creates a new instance ConvolutionPostProcess
  74832. * @param name The name of the effect.
  74833. * @param options The required width/height ratio to downsize to before computing the render pass.
  74834. * @param camera The camera to apply the render pass to.
  74835. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74836. * @param engine The engine which the post process will be applied. (default: current engine)
  74837. * @param reusable If the post process can be reused on the same frame. (default: false)
  74838. * @param textureType Type of textures used when performing the post process. (default: 0)
  74839. * @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)
  74840. */
  74841. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74842. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74843. if (blockCompilation === void 0) { blockCompilation = false; }
  74844. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74845. /**
  74846. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74847. */
  74848. _this.colorAmount = 1.0;
  74849. /**
  74850. * How much sharpness should be applied (default: 0.3)
  74851. */
  74852. _this.edgeAmount = 0.3;
  74853. _this.onApply = function (effect) {
  74854. effect.setFloat2("screenSize", _this.width, _this.height);
  74855. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74856. };
  74857. return _this;
  74858. }
  74859. return SharpenPostProcess;
  74860. }(BABYLON.PostProcess));
  74861. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74862. })(BABYLON || (BABYLON = {}));
  74863. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74864. var BABYLON;
  74865. (function (BABYLON) {
  74866. /**
  74867. * The Blur Post Process which blurs an image based on a kernel and direction.
  74868. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74869. */
  74870. var BlurPostProcess = /** @class */ (function (_super) {
  74871. __extends(BlurPostProcess, _super);
  74872. /**
  74873. * Creates a new instance BlurPostProcess
  74874. * @param name The name of the effect.
  74875. * @param direction The direction in which to blur the image.
  74876. * @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.
  74877. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74878. * @param camera The camera to apply the render pass to.
  74879. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74880. * @param engine The engine which the post process will be applied. (default: current engine)
  74881. * @param reusable If the post process can be reused on the same frame. (default: false)
  74882. * @param textureType Type of textures used when performing the post process. (default: 0)
  74883. * @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)
  74884. */
  74885. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74887. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74888. if (defines === void 0) { defines = ""; }
  74889. if (blockCompilation === void 0) { blockCompilation = false; }
  74890. 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;
  74891. _this.direction = direction;
  74892. _this.blockCompilation = blockCompilation;
  74893. _this._packedFloat = false;
  74894. _this._staticDefines = "";
  74895. _this._staticDefines = defines;
  74896. _this.onApplyObservable.add(function (effect) {
  74897. if (_this._outputTexture) {
  74898. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74899. }
  74900. else {
  74901. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74902. }
  74903. });
  74904. _this.kernel = kernel;
  74905. return _this;
  74906. }
  74907. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74908. /**
  74909. * Gets the length in pixels of the blur sample region
  74910. */
  74911. get: function () {
  74912. return this._idealKernel;
  74913. },
  74914. /**
  74915. * Sets the length in pixels of the blur sample region
  74916. */
  74917. set: function (v) {
  74918. if (this._idealKernel === v) {
  74919. return;
  74920. }
  74921. v = Math.max(v, 1);
  74922. this._idealKernel = v;
  74923. this._kernel = this._nearestBestKernel(v);
  74924. if (!this.blockCompilation) {
  74925. this._updateParameters();
  74926. }
  74927. },
  74928. enumerable: true,
  74929. configurable: true
  74930. });
  74931. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74932. /**
  74933. * Gets wether or not the blur is unpacking/repacking floats
  74934. */
  74935. get: function () {
  74936. return this._packedFloat;
  74937. },
  74938. /**
  74939. * Sets wether or not the blur needs to unpack/repack floats
  74940. */
  74941. set: function (v) {
  74942. if (this._packedFloat === v) {
  74943. return;
  74944. }
  74945. this._packedFloat = v;
  74946. if (!this.blockCompilation) {
  74947. this._updateParameters();
  74948. }
  74949. },
  74950. enumerable: true,
  74951. configurable: true
  74952. });
  74953. /**
  74954. * Updates the effect with the current post process compile time values and recompiles the shader.
  74955. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74956. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74957. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74958. * @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
  74959. * @param onCompiled Called when the shader has been compiled.
  74960. * @param onError Called if there is an error when compiling a shader.
  74961. */
  74962. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74963. if (defines === void 0) { defines = null; }
  74964. if (uniforms === void 0) { uniforms = null; }
  74965. if (samplers === void 0) { samplers = null; }
  74966. this._updateParameters(onCompiled, onError);
  74967. };
  74968. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74969. // Generate sampling offsets and weights
  74970. var N = this._kernel;
  74971. var centerIndex = (N - 1) / 2;
  74972. // Generate Gaussian sampling weights over kernel
  74973. var offsets = [];
  74974. var weights = [];
  74975. var totalWeight = 0;
  74976. for (var i = 0; i < N; i++) {
  74977. var u = i / (N - 1);
  74978. var w = this._gaussianWeight(u * 2.0 - 1);
  74979. offsets[i] = (i - centerIndex);
  74980. weights[i] = w;
  74981. totalWeight += w;
  74982. }
  74983. // Normalize weights
  74984. for (var i = 0; i < weights.length; i++) {
  74985. weights[i] /= totalWeight;
  74986. }
  74987. // Optimize: combine samples to take advantage of hardware linear sampling
  74988. // Walk from left to center, combining pairs (symmetrically)
  74989. var linearSamplingWeights = [];
  74990. var linearSamplingOffsets = [];
  74991. var linearSamplingMap = [];
  74992. for (var i = 0; i <= centerIndex; i += 2) {
  74993. var j = Math.min(i + 1, Math.floor(centerIndex));
  74994. var singleCenterSample = i === j;
  74995. if (singleCenterSample) {
  74996. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74997. }
  74998. else {
  74999. var sharedCell = j === centerIndex;
  75000. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75001. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75002. if (offsetLinear === 0) {
  75003. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75004. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75005. }
  75006. else {
  75007. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75008. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75009. }
  75010. }
  75011. }
  75012. for (var i = 0; i < linearSamplingMap.length; i++) {
  75013. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75014. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75015. }
  75016. // Replace with optimized
  75017. offsets = linearSamplingOffsets;
  75018. weights = linearSamplingWeights;
  75019. // Generate shaders
  75020. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75021. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75022. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75023. var defines = "";
  75024. defines += this._staticDefines;
  75025. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75026. if (this._staticDefines.indexOf("DOF") != -1) {
  75027. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75028. varyingCount--;
  75029. }
  75030. for (var i = 0; i < varyingCount; i++) {
  75031. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75032. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75033. }
  75034. var depCount = 0;
  75035. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75036. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75037. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75038. depCount++;
  75039. }
  75040. if (this.packedFloat) {
  75041. defines += "#define PACKEDFLOAT 1";
  75042. }
  75043. this.blockCompilation = false;
  75044. _super.prototype.updateEffect.call(this, defines, null, null, {
  75045. varyingCount: varyingCount,
  75046. depCount: depCount
  75047. }, onCompiled, onError);
  75048. };
  75049. /**
  75050. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75051. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75052. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75053. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75054. * The gaps between physical kernels are compensated for in the weighting of the samples
  75055. * @param idealKernel Ideal blur kernel.
  75056. * @return Nearest best kernel.
  75057. */
  75058. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75059. var v = Math.round(idealKernel);
  75060. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75061. var k = _a[_i];
  75062. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75063. return Math.max(k, 3);
  75064. }
  75065. }
  75066. return Math.max(v, 3);
  75067. };
  75068. /**
  75069. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75070. * @param x The point on the Gaussian distribution to sample.
  75071. * @return the value of the Gaussian function at x.
  75072. */
  75073. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75074. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75075. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75076. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75077. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75078. // truncated at around 1.3% of peak strength.
  75079. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75080. var sigma = (1 / 3);
  75081. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75082. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75083. var weight = (1.0 / denominator) * Math.exp(exponent);
  75084. return weight;
  75085. };
  75086. /**
  75087. * Generates a string that can be used as a floating point number in GLSL.
  75088. * @param x Value to print.
  75089. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75090. * @return GLSL float string.
  75091. */
  75092. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75093. if (decimalFigures === void 0) { decimalFigures = 8; }
  75094. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75095. };
  75096. return BlurPostProcess;
  75097. }(BABYLON.PostProcess));
  75098. BABYLON.BlurPostProcess = BlurPostProcess;
  75099. })(BABYLON || (BABYLON = {}));
  75100. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75101. var BABYLON;
  75102. (function (BABYLON) {
  75103. /**
  75104. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75105. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75106. * based on samples that have a large difference in distance than the center pixel.
  75107. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75108. */
  75109. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75110. __extends(DepthOfFieldBlurPostProcess, _super);
  75111. /**
  75112. * Creates a new instance CircleOfConfusionPostProcess
  75113. * @param name The name of the effect.
  75114. * @param scene The scene the effect belongs to.
  75115. * @param direction The direction the blur should be applied.
  75116. * @param kernel The size of the kernel used to blur.
  75117. * @param options The required width/height ratio to downsize to before computing the render pass.
  75118. * @param camera The camera to apply the render pass to.
  75119. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75120. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75121. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75122. * @param engine The engine which the post process will be applied. (default: current engine)
  75123. * @param reusable If the post process can be reused on the same frame. (default: false)
  75124. * @param textureType Type of textures used when performing the post process. (default: 0)
  75125. * @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)
  75126. */
  75127. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75128. if (imageToBlur === void 0) { imageToBlur = null; }
  75129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75130. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75131. if (blockCompilation === void 0) { blockCompilation = false; }
  75132. 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;
  75133. _this.direction = direction;
  75134. _this.onApplyObservable.add(function (effect) {
  75135. if (imageToBlur != null) {
  75136. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75137. }
  75138. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75139. if (scene.activeCamera) {
  75140. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75141. }
  75142. });
  75143. return _this;
  75144. }
  75145. return DepthOfFieldBlurPostProcess;
  75146. }(BABYLON.BlurPostProcess));
  75147. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75148. })(BABYLON || (BABYLON = {}));
  75149. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75150. var BABYLON;
  75151. (function (BABYLON) {
  75152. /**
  75153. * Options to be set when merging outputs from the default pipeline.
  75154. */
  75155. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75156. function DepthOfFieldMergePostProcessOptions() {
  75157. }
  75158. return DepthOfFieldMergePostProcessOptions;
  75159. }());
  75160. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75161. /**
  75162. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75163. */
  75164. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75165. __extends(DepthOfFieldMergePostProcess, _super);
  75166. /**
  75167. * Creates a new instance of DepthOfFieldMergePostProcess
  75168. * @param name The name of the effect.
  75169. * @param originalFromInput Post process which's input will be used for the merge.
  75170. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75171. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75172. * @param options The required width/height ratio to downsize to before computing the render pass.
  75173. * @param camera The camera to apply the render pass to.
  75174. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75175. * @param engine The engine which the post process will be applied. (default: current engine)
  75176. * @param reusable If the post process can be reused on the same frame. (default: false)
  75177. * @param textureType Type of textures used when performing the post process. (default: 0)
  75178. * @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)
  75179. */
  75180. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75181. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75182. if (blockCompilation === void 0) { blockCompilation = false; }
  75183. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75184. _this.blurSteps = blurSteps;
  75185. _this.onApplyObservable.add(function (effect) {
  75186. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75187. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75188. blurSteps.forEach(function (step, index) {
  75189. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75190. });
  75191. });
  75192. if (!blockCompilation) {
  75193. _this.updateEffect();
  75194. }
  75195. return _this;
  75196. }
  75197. /**
  75198. * Updates the effect with the current post process compile time values and recompiles the shader.
  75199. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75200. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75201. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75202. * @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
  75203. * @param onCompiled Called when the shader has been compiled.
  75204. * @param onError Called if there is an error when compiling a shader.
  75205. */
  75206. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75207. if (defines === void 0) { defines = null; }
  75208. if (uniforms === void 0) { uniforms = null; }
  75209. if (samplers === void 0) { samplers = null; }
  75210. if (!defines) {
  75211. defines = "";
  75212. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75213. }
  75214. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75215. };
  75216. return DepthOfFieldMergePostProcess;
  75217. }(BABYLON.PostProcess));
  75218. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75219. })(BABYLON || (BABYLON = {}));
  75220. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75221. var BABYLON;
  75222. (function (BABYLON) {
  75223. /**
  75224. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75225. */
  75226. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75227. __extends(CircleOfConfusionPostProcess, _super);
  75228. /**
  75229. * Creates a new instance CircleOfConfusionPostProcess
  75230. * @param name The name of the effect.
  75231. * @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.
  75232. * @param options The required width/height ratio to downsize to before computing the render pass.
  75233. * @param camera The camera to apply the render pass to.
  75234. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75235. * @param engine The engine which the post process will be applied. (default: current engine)
  75236. * @param reusable If the post process can be reused on the same frame. (default: false)
  75237. * @param textureType Type of textures used when performing the post process. (default: 0)
  75238. * @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)
  75239. */
  75240. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75241. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75242. if (blockCompilation === void 0) { blockCompilation = false; }
  75243. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75244. /**
  75245. * 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.
  75246. */
  75247. _this.lensSize = 50;
  75248. /**
  75249. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75250. */
  75251. _this.fStop = 1.4;
  75252. /**
  75253. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75254. */
  75255. _this.focusDistance = 2000;
  75256. /**
  75257. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75258. */
  75259. _this.focalLength = 50;
  75260. _this._depthTexture = null;
  75261. _this._depthTexture = depthTexture;
  75262. _this.onApplyObservable.add(function (effect) {
  75263. if (!_this._depthTexture) {
  75264. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75265. return;
  75266. }
  75267. effect.setTexture("depthSampler", _this._depthTexture);
  75268. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75269. var aperture = _this.lensSize / _this.fStop;
  75270. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75271. effect.setFloat('focusDistance', _this.focusDistance);
  75272. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75273. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75274. });
  75275. return _this;
  75276. }
  75277. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75278. /**
  75279. * 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.
  75280. */
  75281. set: function (value) {
  75282. this._depthTexture = value;
  75283. },
  75284. enumerable: true,
  75285. configurable: true
  75286. });
  75287. return CircleOfConfusionPostProcess;
  75288. }(BABYLON.PostProcess));
  75289. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75290. })(BABYLON || (BABYLON = {}));
  75291. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75292. var BABYLON;
  75293. (function (BABYLON) {
  75294. /**
  75295. * Specifies the level of max blur that should be applied when using the depth of field effect
  75296. */
  75297. var DepthOfFieldEffectBlurLevel;
  75298. (function (DepthOfFieldEffectBlurLevel) {
  75299. /**
  75300. * Subtle blur
  75301. */
  75302. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75303. /**
  75304. * Medium blur
  75305. */
  75306. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75307. /**
  75308. * Large blur
  75309. */
  75310. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75311. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75312. ;
  75313. /**
  75314. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75315. */
  75316. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75317. __extends(DepthOfFieldEffect, _super);
  75318. /**
  75319. * Creates a new instance DepthOfFieldEffect
  75320. * @param scene The scene the effect belongs to.
  75321. * @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.
  75322. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75323. * @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)
  75324. */
  75325. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75326. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75327. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75328. if (blockCompilation === void 0) { blockCompilation = false; }
  75329. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75330. return _this._effects;
  75331. }, true) || this;
  75332. /**
  75333. * Internal post processes in depth of field effect
  75334. */
  75335. _this._effects = [];
  75336. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75337. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75338. // 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)
  75339. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75340. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75341. _this._depthOfFieldBlurY = [];
  75342. _this._depthOfFieldBlurX = [];
  75343. var blurCount = 1;
  75344. var kernelSize = 15;
  75345. switch (blurLevel) {
  75346. case DepthOfFieldEffectBlurLevel.High: {
  75347. blurCount = 3;
  75348. kernelSize = 51;
  75349. break;
  75350. }
  75351. case DepthOfFieldEffectBlurLevel.Medium: {
  75352. blurCount = 2;
  75353. kernelSize = 31;
  75354. break;
  75355. }
  75356. default: {
  75357. kernelSize = 15;
  75358. blurCount = 1;
  75359. break;
  75360. }
  75361. }
  75362. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75363. var ratio = 1.0;
  75364. for (var i = 0; i < blurCount; i++) {
  75365. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75366. blurY.autoClear = false;
  75367. ratio = 0.75 / Math.pow(2, i);
  75368. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75369. blurX.autoClear = false;
  75370. _this._depthOfFieldBlurY.push(blurY);
  75371. _this._depthOfFieldBlurX.push(blurX);
  75372. }
  75373. // Set all post processes on the effect.
  75374. _this._effects = [_this._circleOfConfusion];
  75375. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75376. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75377. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75378. }
  75379. // Merge blurred images with original image based on circleOfConfusion
  75380. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75381. _this._dofMerge.autoClear = false;
  75382. _this._effects.push(_this._dofMerge);
  75383. return _this;
  75384. }
  75385. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75386. get: function () {
  75387. return this._circleOfConfusion.focalLength;
  75388. },
  75389. /**
  75390. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75391. */
  75392. set: function (value) {
  75393. this._circleOfConfusion.focalLength = value;
  75394. },
  75395. enumerable: true,
  75396. configurable: true
  75397. });
  75398. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75399. get: function () {
  75400. return this._circleOfConfusion.fStop;
  75401. },
  75402. /**
  75403. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75404. */
  75405. set: function (value) {
  75406. this._circleOfConfusion.fStop = value;
  75407. },
  75408. enumerable: true,
  75409. configurable: true
  75410. });
  75411. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75412. get: function () {
  75413. return this._circleOfConfusion.focusDistance;
  75414. },
  75415. /**
  75416. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75417. */
  75418. set: function (value) {
  75419. this._circleOfConfusion.focusDistance = value;
  75420. },
  75421. enumerable: true,
  75422. configurable: true
  75423. });
  75424. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75425. get: function () {
  75426. return this._circleOfConfusion.lensSize;
  75427. },
  75428. /**
  75429. * 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.
  75430. */
  75431. set: function (value) {
  75432. this._circleOfConfusion.lensSize = value;
  75433. },
  75434. enumerable: true,
  75435. configurable: true
  75436. });
  75437. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75438. /**
  75439. * 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.
  75440. */
  75441. set: function (value) {
  75442. this._circleOfConfusion.depthTexture = value;
  75443. },
  75444. enumerable: true,
  75445. configurable: true
  75446. });
  75447. /**
  75448. * Disposes each of the internal effects for a given camera.
  75449. * @param camera The camera to dispose the effect on.
  75450. */
  75451. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75452. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75453. this._effects[effectIndex].dispose(camera);
  75454. }
  75455. };
  75456. /**
  75457. * Internal
  75458. */
  75459. DepthOfFieldEffect.prototype._updateEffects = function () {
  75460. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75461. this._effects[effectIndex].updateEffect();
  75462. }
  75463. };
  75464. /**
  75465. * Internal
  75466. * @returns if all the contained post processes are ready.
  75467. */
  75468. DepthOfFieldEffect.prototype._isReady = function () {
  75469. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75470. if (!this._effects[effectIndex].isReady()) {
  75471. return false;
  75472. }
  75473. }
  75474. return true;
  75475. };
  75476. return DepthOfFieldEffect;
  75477. }(BABYLON.PostProcessRenderEffect));
  75478. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75479. })(BABYLON || (BABYLON = {}));
  75480. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75481. var BABYLON;
  75482. (function (BABYLON) {
  75483. /**
  75484. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75485. */
  75486. var BloomMergePostProcess = /** @class */ (function (_super) {
  75487. __extends(BloomMergePostProcess, _super);
  75488. /**
  75489. * Creates a new instance of @see BloomMergePostProcess
  75490. * @param name The name of the effect.
  75491. * @param originalFromInput Post process which's input will be used for the merge.
  75492. * @param blurred Blurred highlights post process which's output will be used.
  75493. * @param weight Weight of the bloom to be added to the original input.
  75494. * @param options The required width/height ratio to downsize to before computing the render pass.
  75495. * @param camera The camera to apply the render pass to.
  75496. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75497. * @param engine The engine which the post process will be applied. (default: current engine)
  75498. * @param reusable If the post process can be reused on the same frame. (default: false)
  75499. * @param textureType Type of textures used when performing the post process. (default: 0)
  75500. * @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)
  75501. */
  75502. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75504. if (blockCompilation === void 0) { blockCompilation = false; }
  75505. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75506. _this.weight = weight;
  75507. _this.onApplyObservable.add(function (effect) {
  75508. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75509. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75510. effect.setFloat("bloomWeight", _this.weight);
  75511. });
  75512. if (!blockCompilation) {
  75513. _this.updateEffect();
  75514. }
  75515. return _this;
  75516. }
  75517. return BloomMergePostProcess;
  75518. }(BABYLON.PostProcess));
  75519. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75520. })(BABYLON || (BABYLON = {}));
  75521. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75522. var BABYLON;
  75523. (function (BABYLON) {
  75524. /**
  75525. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75526. */
  75527. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75528. __extends(ExtractHighlightsPostProcess, _super);
  75529. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75530. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75531. if (blockCompilation === void 0) { blockCompilation = false; }
  75532. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75533. /**
  75534. * The luminance threshold, pixels below this value will be set to black.
  75535. */
  75536. _this.threshold = 0.9;
  75537. /**
  75538. * Internal
  75539. */
  75540. _this._exposure = 1;
  75541. /**
  75542. * Post process which has the input texture to be used when performing highlight extraction
  75543. */
  75544. _this._inputPostProcess = null;
  75545. _this.onApplyObservable.add(function (effect) {
  75546. if (_this._inputPostProcess) {
  75547. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75548. }
  75549. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75550. effect.setFloat('exposure', _this._exposure);
  75551. });
  75552. return _this;
  75553. }
  75554. return ExtractHighlightsPostProcess;
  75555. }(BABYLON.PostProcess));
  75556. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75557. })(BABYLON || (BABYLON = {}));
  75558. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75559. var BABYLON;
  75560. (function (BABYLON) {
  75561. /**
  75562. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75563. */
  75564. var BloomEffect = /** @class */ (function (_super) {
  75565. __extends(BloomEffect, _super);
  75566. /**
  75567. * Creates a new instance of @see BloomEffect
  75568. * @param scene The scene the effect belongs to.
  75569. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75570. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75571. * @param bloomWeight The the strength of bloom.
  75572. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75573. * @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)
  75574. */
  75575. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75576. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75577. if (blockCompilation === void 0) { blockCompilation = false; }
  75578. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75579. return _this._effects;
  75580. }, true) || this;
  75581. _this.bloomScale = bloomScale;
  75582. /**
  75583. * Internal
  75584. */
  75585. _this._effects = [];
  75586. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75587. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75588. _this._blurX.alwaysForcePOT = true;
  75589. _this._blurX.autoClear = false;
  75590. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75591. _this._blurY.alwaysForcePOT = true;
  75592. _this._blurY.autoClear = false;
  75593. _this.kernel = bloomKernel;
  75594. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75595. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75596. _this._merge.autoClear = false;
  75597. _this._effects.push(_this._merge);
  75598. return _this;
  75599. }
  75600. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75601. /**
  75602. * The luminance threshold to find bright areas of the image to bloom.
  75603. */
  75604. get: function () {
  75605. return this._downscale.threshold;
  75606. },
  75607. set: function (value) {
  75608. this._downscale.threshold = value;
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. Object.defineProperty(BloomEffect.prototype, "weight", {
  75614. /**
  75615. * The strength of the bloom.
  75616. */
  75617. get: function () {
  75618. return this._merge.weight;
  75619. },
  75620. set: function (value) {
  75621. this._merge.weight = value;
  75622. },
  75623. enumerable: true,
  75624. configurable: true
  75625. });
  75626. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75627. /**
  75628. * Specifies the size of the bloom blur kernel, relative to the final output size
  75629. */
  75630. get: function () {
  75631. return this._blurX.kernel / this.bloomScale;
  75632. },
  75633. set: function (value) {
  75634. this._blurX.kernel = value * this.bloomScale;
  75635. this._blurY.kernel = value * this.bloomScale;
  75636. },
  75637. enumerable: true,
  75638. configurable: true
  75639. });
  75640. /**
  75641. * Disposes each of the internal effects for a given camera.
  75642. * @param camera The camera to dispose the effect on.
  75643. */
  75644. BloomEffect.prototype.disposeEffects = function (camera) {
  75645. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75646. this._effects[effectIndex].dispose(camera);
  75647. }
  75648. };
  75649. /**
  75650. * Internal
  75651. */
  75652. BloomEffect.prototype._updateEffects = function () {
  75653. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75654. this._effects[effectIndex].updateEffect();
  75655. }
  75656. };
  75657. /**
  75658. * Internal
  75659. * @returns if all the contained post processes are ready.
  75660. */
  75661. BloomEffect.prototype._isReady = function () {
  75662. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75663. if (!this._effects[effectIndex].isReady()) {
  75664. return false;
  75665. }
  75666. }
  75667. return true;
  75668. };
  75669. return BloomEffect;
  75670. }(BABYLON.PostProcessRenderEffect));
  75671. BABYLON.BloomEffect = BloomEffect;
  75672. })(BABYLON || (BABYLON = {}));
  75673. //# sourceMappingURL=babylon.bloomEffect.js.map
  75674. var BABYLON;
  75675. (function (BABYLON) {
  75676. /**
  75677. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75678. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75679. */
  75680. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75681. __extends(DefaultRenderingPipeline, _super);
  75682. /**
  75683. * @constructor
  75684. * @param {string} name - The rendering pipeline name (default: "")
  75685. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75686. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75687. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75688. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75689. */
  75690. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75691. if (name === void 0) { name = ""; }
  75692. if (hdr === void 0) { hdr = true; }
  75693. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75694. if (automaticBuild === void 0) { automaticBuild = true; }
  75695. var _this = _super.call(this, scene.getEngine(), name) || this;
  75696. _this._originalCameras = [];
  75697. /**
  75698. * ID of the sharpen post process,
  75699. */
  75700. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75701. /**
  75702. * ID of the image processing post process;
  75703. */
  75704. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75705. /**
  75706. * ID of the Fast Approximate Anti-Aliasing post process;
  75707. */
  75708. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75709. /**
  75710. * ID of the chromatic aberration post process,
  75711. */
  75712. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75713. /**
  75714. * ID of the grain post process
  75715. */
  75716. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75717. /**
  75718. * Glow post process which adds a glow to emmisive areas of the image
  75719. */
  75720. _this._glowLayer = null;
  75721. /**
  75722. * Animations which can be used to tweak settings over a period of time
  75723. */
  75724. _this.animations = [];
  75725. _this._imageProcessingConfigurationObserver = null;
  75726. // Values
  75727. _this._sharpenEnabled = false;
  75728. _this._bloomEnabled = false;
  75729. _this._depthOfFieldEnabled = false;
  75730. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75731. _this._fxaaEnabled = false;
  75732. _this._imageProcessingEnabled = true;
  75733. _this._bloomScale = 0.5;
  75734. _this._chromaticAberrationEnabled = false;
  75735. _this._grainEnabled = false;
  75736. _this._buildAllowed = true;
  75737. _this._resizeObserver = null;
  75738. _this._hardwareScaleLevel = 1.0;
  75739. _this._bloomKernel = 64;
  75740. /**
  75741. * Specifies the weight of the bloom in the final rendering
  75742. */
  75743. _this._bloomWeight = 0.15;
  75744. /**
  75745. * Specifies the luma threshold for the area that will be blurred by the bloom
  75746. */
  75747. _this._bloomThreshold = 0.9;
  75748. _this._samples = 1;
  75749. _this._hasCleared = false;
  75750. _this._prevPostProcess = null;
  75751. _this._prevPrevPostProcess = null;
  75752. _this._cameras = cameras || scene.cameras;
  75753. _this._originalCameras = _this._cameras.slice();
  75754. _this._buildAllowed = automaticBuild;
  75755. // Initialize
  75756. _this._scene = scene;
  75757. var caps = _this._scene.getEngine().getCaps();
  75758. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75759. // Misc
  75760. if (_this._hdr) {
  75761. if (caps.textureHalfFloatRender) {
  75762. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75763. }
  75764. else if (caps.textureFloatRender) {
  75765. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75766. }
  75767. }
  75768. else {
  75769. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75770. }
  75771. // Attach
  75772. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75773. var engine = _this._scene.getEngine();
  75774. // Create post processes before hand so they can be modified before enabled.
  75775. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75776. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75777. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75778. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75779. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75780. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75781. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75782. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75783. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75784. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75785. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75786. _this.bloomKernel = _this.bloomKernel;
  75787. });
  75788. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75789. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75790. });
  75791. _this._buildPipeline();
  75792. return _this;
  75793. }
  75794. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75795. get: function () {
  75796. return this._sharpenEnabled;
  75797. },
  75798. /**
  75799. * Enable or disable the sharpen process from the pipeline
  75800. */
  75801. set: function (enabled) {
  75802. if (this._sharpenEnabled === enabled) {
  75803. return;
  75804. }
  75805. this._sharpenEnabled = enabled;
  75806. this._buildPipeline();
  75807. },
  75808. enumerable: true,
  75809. configurable: true
  75810. });
  75811. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75812. /**
  75813. * Specifies the size of the bloom blur kernel, relative to the final output size
  75814. */
  75815. get: function () {
  75816. return this._bloomKernel;
  75817. },
  75818. set: function (value) {
  75819. this._bloomKernel = value;
  75820. this.bloom.kernel = value / this._hardwareScaleLevel;
  75821. },
  75822. enumerable: true,
  75823. configurable: true
  75824. });
  75825. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75826. get: function () {
  75827. return this._bloomWeight;
  75828. },
  75829. /**
  75830. * The strength of the bloom.
  75831. */
  75832. set: function (value) {
  75833. if (this._bloomWeight === value) {
  75834. return;
  75835. }
  75836. this.bloom.weight = value;
  75837. this._bloomWeight = value;
  75838. },
  75839. enumerable: true,
  75840. configurable: true
  75841. });
  75842. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75843. get: function () {
  75844. return this._bloomThreshold;
  75845. },
  75846. /**
  75847. * The strength of the bloom.
  75848. */
  75849. set: function (value) {
  75850. if (this._bloomThreshold === value) {
  75851. return;
  75852. }
  75853. this.bloom.threshold = value;
  75854. this._bloomThreshold = value;
  75855. },
  75856. enumerable: true,
  75857. configurable: true
  75858. });
  75859. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75860. get: function () {
  75861. return this._bloomScale;
  75862. },
  75863. /**
  75864. * The scale of the bloom, lower value will provide better performance.
  75865. */
  75866. set: function (value) {
  75867. if (this._bloomScale === value) {
  75868. return;
  75869. }
  75870. this._bloomScale = value;
  75871. // recreate bloom and dispose old as this setting is not dynamic
  75872. this._rebuildBloom();
  75873. this._buildPipeline();
  75874. },
  75875. enumerable: true,
  75876. configurable: true
  75877. });
  75878. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75879. get: function () {
  75880. return this._bloomEnabled;
  75881. },
  75882. /**
  75883. * Enable or disable the bloom from the pipeline
  75884. */
  75885. set: function (enabled) {
  75886. if (this._bloomEnabled === enabled) {
  75887. return;
  75888. }
  75889. this._bloomEnabled = enabled;
  75890. this._buildPipeline();
  75891. },
  75892. enumerable: true,
  75893. configurable: true
  75894. });
  75895. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75896. // recreate bloom and dispose old as this setting is not dynamic
  75897. var oldBloom = this.bloom;
  75898. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75899. this.bloom.threshold = oldBloom.threshold;
  75900. for (var i = 0; i < this._cameras.length; i++) {
  75901. oldBloom.disposeEffects(this._cameras[i]);
  75902. }
  75903. };
  75904. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75905. /**
  75906. * If the depth of field is enabled.
  75907. */
  75908. get: function () {
  75909. return this._depthOfFieldEnabled;
  75910. },
  75911. set: function (enabled) {
  75912. if (this._depthOfFieldEnabled === enabled) {
  75913. return;
  75914. }
  75915. this._depthOfFieldEnabled = enabled;
  75916. this._buildPipeline();
  75917. },
  75918. enumerable: true,
  75919. configurable: true
  75920. });
  75921. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75922. /**
  75923. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75924. */
  75925. get: function () {
  75926. return this._depthOfFieldBlurLevel;
  75927. },
  75928. set: function (value) {
  75929. if (this._depthOfFieldBlurLevel === value) {
  75930. return;
  75931. }
  75932. this._depthOfFieldBlurLevel = value;
  75933. // recreate dof and dispose old as this setting is not dynamic
  75934. var oldDof = this.depthOfField;
  75935. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75936. this.depthOfField.focalLength = oldDof.focalLength;
  75937. this.depthOfField.focusDistance = oldDof.focusDistance;
  75938. this.depthOfField.fStop = oldDof.fStop;
  75939. this.depthOfField.lensSize = oldDof.lensSize;
  75940. for (var i = 0; i < this._cameras.length; i++) {
  75941. oldDof.disposeEffects(this._cameras[i]);
  75942. }
  75943. this._buildPipeline();
  75944. },
  75945. enumerable: true,
  75946. configurable: true
  75947. });
  75948. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75949. get: function () {
  75950. return this._fxaaEnabled;
  75951. },
  75952. /**
  75953. * If the anti aliasing is enabled.
  75954. */
  75955. set: function (enabled) {
  75956. if (this._fxaaEnabled === enabled) {
  75957. return;
  75958. }
  75959. this._fxaaEnabled = enabled;
  75960. this._buildPipeline();
  75961. },
  75962. enumerable: true,
  75963. configurable: true
  75964. });
  75965. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75966. get: function () {
  75967. return this._samples;
  75968. },
  75969. /**
  75970. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75971. */
  75972. set: function (sampleCount) {
  75973. if (this._samples === sampleCount) {
  75974. return;
  75975. }
  75976. this._samples = sampleCount;
  75977. this._buildPipeline();
  75978. },
  75979. enumerable: true,
  75980. configurable: true
  75981. });
  75982. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75983. get: function () {
  75984. return this._imageProcessingEnabled;
  75985. },
  75986. /**
  75987. * If image processing is enabled.
  75988. */
  75989. set: function (enabled) {
  75990. if (this._imageProcessingEnabled === enabled) {
  75991. return;
  75992. }
  75993. this._imageProcessingEnabled = enabled;
  75994. this._buildPipeline();
  75995. },
  75996. enumerable: true,
  75997. configurable: true
  75998. });
  75999. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76000. get: function () {
  76001. return this._glowLayer == null;
  76002. },
  76003. /**
  76004. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76005. */
  76006. set: function (enabled) {
  76007. if (enabled && !this._glowLayer) {
  76008. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76009. }
  76010. else if (!enabled && this._glowLayer) {
  76011. this._glowLayer.dispose();
  76012. this._glowLayer = null;
  76013. }
  76014. },
  76015. enumerable: true,
  76016. configurable: true
  76017. });
  76018. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76019. get: function () {
  76020. return this._chromaticAberrationEnabled;
  76021. },
  76022. /**
  76023. * Enable or disable the chromaticAberration process from the pipeline
  76024. */
  76025. set: function (enabled) {
  76026. if (this._chromaticAberrationEnabled === enabled) {
  76027. return;
  76028. }
  76029. this._chromaticAberrationEnabled = enabled;
  76030. this._buildPipeline();
  76031. },
  76032. enumerable: true,
  76033. configurable: true
  76034. });
  76035. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76036. get: function () {
  76037. return this._grainEnabled;
  76038. },
  76039. /**
  76040. * Enable or disable the grain process from the pipeline
  76041. */
  76042. set: function (enabled) {
  76043. if (this._grainEnabled === enabled) {
  76044. return;
  76045. }
  76046. this._grainEnabled = enabled;
  76047. this._buildPipeline();
  76048. },
  76049. enumerable: true,
  76050. configurable: true
  76051. });
  76052. /**
  76053. * Force the compilation of the entire pipeline.
  76054. */
  76055. DefaultRenderingPipeline.prototype.prepare = function () {
  76056. var previousState = this._buildAllowed;
  76057. this._buildAllowed = true;
  76058. this._buildPipeline();
  76059. this._buildAllowed = previousState;
  76060. };
  76061. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76062. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76063. if (this._hasCleared) {
  76064. postProcess.autoClear = false;
  76065. }
  76066. else {
  76067. postProcess.autoClear = true;
  76068. this._scene.autoClear = false;
  76069. this._hasCleared = true;
  76070. }
  76071. if (!skipTextureSharing) {
  76072. if (this._prevPrevPostProcess) {
  76073. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76074. }
  76075. else {
  76076. postProcess.useOwnOutput();
  76077. }
  76078. if (this._prevPostProcess) {
  76079. this._prevPrevPostProcess = this._prevPostProcess;
  76080. }
  76081. this._prevPostProcess = postProcess;
  76082. }
  76083. };
  76084. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76085. var _this = this;
  76086. if (!this._buildAllowed) {
  76087. return;
  76088. }
  76089. this._scene.autoClear = true;
  76090. var engine = this._scene.getEngine();
  76091. this._disposePostProcesses();
  76092. if (this._cameras !== null) {
  76093. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76094. // get back cameras to be used to reattach pipeline
  76095. this._cameras = this._originalCameras.slice();
  76096. }
  76097. this._reset();
  76098. this._prevPostProcess = null;
  76099. this._prevPrevPostProcess = null;
  76100. this._hasCleared = false;
  76101. if (this.depthOfFieldEnabled) {
  76102. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76103. this.depthOfField.depthTexture = depthTexture;
  76104. if (!this.depthOfField._isReady()) {
  76105. this.depthOfField._updateEffects();
  76106. }
  76107. this.addEffect(this.depthOfField);
  76108. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76109. }
  76110. if (this.bloomEnabled) {
  76111. if (!this.bloom._isReady()) {
  76112. this.bloom._updateEffects();
  76113. }
  76114. this.addEffect(this.bloom);
  76115. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76116. }
  76117. if (this._imageProcessingEnabled) {
  76118. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76119. if (this._hdr) {
  76120. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76121. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76122. }
  76123. else {
  76124. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76125. }
  76126. }
  76127. if (this.sharpenEnabled) {
  76128. if (!this.sharpen.isReady()) {
  76129. this.sharpen.updateEffect();
  76130. }
  76131. this.addEffect(this._sharpenEffect);
  76132. this._setAutoClearAndTextureSharing(this.sharpen);
  76133. }
  76134. if (this.grainEnabled) {
  76135. if (!this.grain.isReady()) {
  76136. this.grain.updateEffect();
  76137. }
  76138. this.addEffect(this._grainEffect);
  76139. this._setAutoClearAndTextureSharing(this.grain);
  76140. }
  76141. if (this.chromaticAberrationEnabled) {
  76142. if (!this.chromaticAberration.isReady()) {
  76143. this.chromaticAberration.updateEffect();
  76144. }
  76145. this.addEffect(this._chromaticAberrationEffect);
  76146. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76147. }
  76148. if (this.fxaaEnabled) {
  76149. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76150. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76151. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76152. }
  76153. if (this._cameras !== null) {
  76154. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76155. }
  76156. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76157. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76158. }
  76159. };
  76160. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76161. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76162. for (var i = 0; i < this._cameras.length; i++) {
  76163. var camera = this._cameras[i];
  76164. if (this.imageProcessing) {
  76165. this.imageProcessing.dispose(camera);
  76166. }
  76167. if (this.fxaa) {
  76168. this.fxaa.dispose(camera);
  76169. }
  76170. // These are created in the constructor and should not be disposed on every pipeline change
  76171. if (disposeNonRecreated) {
  76172. if (this.sharpen) {
  76173. this.sharpen.dispose(camera);
  76174. }
  76175. if (this.depthOfField) {
  76176. this.depthOfField.disposeEffects(camera);
  76177. }
  76178. if (this.bloom) {
  76179. this.bloom.disposeEffects(camera);
  76180. }
  76181. if (this.chromaticAberration) {
  76182. this.chromaticAberration.dispose(camera);
  76183. }
  76184. if (this.grain) {
  76185. this.grain.dispose(camera);
  76186. }
  76187. if (this._glowLayer) {
  76188. this._glowLayer.dispose();
  76189. }
  76190. }
  76191. }
  76192. this.imageProcessing = null;
  76193. this.fxaa = null;
  76194. if (disposeNonRecreated) {
  76195. this.sharpen = null;
  76196. this._sharpenEffect = null;
  76197. this.depthOfField = null;
  76198. this.bloom = null;
  76199. this.chromaticAberration = null;
  76200. this._chromaticAberrationEffect = null;
  76201. this.grain = null;
  76202. this._grainEffect = null;
  76203. this._glowLayer = null;
  76204. }
  76205. };
  76206. /**
  76207. * Dispose of the pipeline and stop all post processes
  76208. */
  76209. DefaultRenderingPipeline.prototype.dispose = function () {
  76210. this._disposePostProcesses(true);
  76211. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76212. this._scene.autoClear = true;
  76213. if (this._resizeObserver) {
  76214. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76215. this._resizeObserver = null;
  76216. }
  76217. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76218. _super.prototype.dispose.call(this);
  76219. };
  76220. /**
  76221. * Serialize the rendering pipeline (Used when exporting)
  76222. * @returns the serialized object
  76223. */
  76224. DefaultRenderingPipeline.prototype.serialize = function () {
  76225. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76226. serializationObject.customType = "DefaultRenderingPipeline";
  76227. return serializationObject;
  76228. };
  76229. /**
  76230. * Parse the serialized pipeline
  76231. * @param source Source pipeline.
  76232. * @param scene The scene to load the pipeline to.
  76233. * @param rootUrl The URL of the serialized pipeline.
  76234. * @returns An instantiated pipeline from the serialized object.
  76235. */
  76236. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76237. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76238. };
  76239. __decorate([
  76240. BABYLON.serialize()
  76241. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76242. __decorate([
  76243. BABYLON.serialize()
  76244. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76245. __decorate([
  76246. BABYLON.serialize()
  76247. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76248. __decorate([
  76249. BABYLON.serialize()
  76250. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76251. __decorate([
  76252. BABYLON.serialize()
  76253. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76254. __decorate([
  76255. BABYLON.serialize()
  76256. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76257. __decorate([
  76258. BABYLON.serialize()
  76259. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76260. __decorate([
  76261. BABYLON.serialize()
  76262. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76263. __decorate([
  76264. BABYLON.serialize()
  76265. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76266. __decorate([
  76267. BABYLON.serialize()
  76268. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76269. __decorate([
  76270. BABYLON.serialize()
  76271. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76272. __decorate([
  76273. BABYLON.serialize()
  76274. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76275. __decorate([
  76276. BABYLON.serialize()
  76277. ], DefaultRenderingPipeline.prototype, "samples", null);
  76278. __decorate([
  76279. BABYLON.serialize()
  76280. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76281. __decorate([
  76282. BABYLON.serialize()
  76283. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76284. __decorate([
  76285. BABYLON.serialize()
  76286. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76287. __decorate([
  76288. BABYLON.serialize()
  76289. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76290. return DefaultRenderingPipeline;
  76291. }(BABYLON.PostProcessRenderPipeline));
  76292. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76293. })(BABYLON || (BABYLON = {}));
  76294. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76295. var BABYLON;
  76296. (function (BABYLON) {
  76297. /**
  76298. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76299. */
  76300. var GeometryBufferRenderer = /** @class */ (function () {
  76301. /**
  76302. * Creates a new G Buffer for the scene
  76303. * @param scene The scene the buffer belongs to
  76304. * @param ratio How big is the buffer related to the main canvas.
  76305. */
  76306. function GeometryBufferRenderer(scene, ratio) {
  76307. if (ratio === void 0) { ratio = 1; }
  76308. this._enablePosition = false;
  76309. this._scene = scene;
  76310. this._ratio = ratio;
  76311. // Render target
  76312. this._createRenderTargets();
  76313. }
  76314. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76315. /**
  76316. * Set the render list (meshes to be rendered) used in the G buffer.
  76317. */
  76318. set: function (meshes) {
  76319. this._multiRenderTarget.renderList = meshes;
  76320. },
  76321. enumerable: true,
  76322. configurable: true
  76323. });
  76324. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76325. /**
  76326. * Gets wether or not G buffer are supported by the running hardware.
  76327. * This requires draw buffer supports
  76328. */
  76329. get: function () {
  76330. return this._multiRenderTarget.isSupported;
  76331. },
  76332. enumerable: true,
  76333. configurable: true
  76334. });
  76335. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76336. /**
  76337. * Gets wether or not position are enabled for the G buffer.
  76338. */
  76339. get: function () {
  76340. return this._enablePosition;
  76341. },
  76342. /**
  76343. * Sets wether or not position are enabled for the G buffer.
  76344. */
  76345. set: function (enable) {
  76346. this._enablePosition = enable;
  76347. this.dispose();
  76348. this._createRenderTargets();
  76349. },
  76350. enumerable: true,
  76351. configurable: true
  76352. });
  76353. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76354. /**
  76355. * Gets the scene associated with the buffer.
  76356. */
  76357. get: function () {
  76358. return this._scene;
  76359. },
  76360. enumerable: true,
  76361. configurable: true
  76362. });
  76363. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76364. /**
  76365. * Gets the ratio used by the buffer during its creation.
  76366. * How big is the buffer related to the main canvas.
  76367. */
  76368. get: function () {
  76369. return this._ratio;
  76370. },
  76371. enumerable: true,
  76372. configurable: true
  76373. });
  76374. /**
  76375. * Checks wether everything is ready to render a submesh to the G buffer.
  76376. * @param subMesh the submesh to check readiness for
  76377. * @param useInstances is the mesh drawn using instance or not
  76378. * @returns true if ready otherwise false
  76379. */
  76380. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76381. var material = subMesh.getMaterial();
  76382. if (material && material.disableDepthWrite) {
  76383. return false;
  76384. }
  76385. var defines = [];
  76386. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76387. var mesh = subMesh.getMesh();
  76388. // Alpha test
  76389. if (material && material.needAlphaTesting()) {
  76390. defines.push("#define ALPHATEST");
  76391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76392. attribs.push(BABYLON.VertexBuffer.UVKind);
  76393. defines.push("#define UV1");
  76394. }
  76395. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76396. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76397. defines.push("#define UV2");
  76398. }
  76399. }
  76400. // Buffers
  76401. if (this._enablePosition) {
  76402. defines.push("#define POSITION");
  76403. }
  76404. // Bones
  76405. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76406. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76407. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76408. if (mesh.numBoneInfluencers > 4) {
  76409. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76410. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76411. }
  76412. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76413. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76414. }
  76415. else {
  76416. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76417. }
  76418. // Instances
  76419. if (useInstances) {
  76420. defines.push("#define INSTANCES");
  76421. attribs.push("world0");
  76422. attribs.push("world1");
  76423. attribs.push("world2");
  76424. attribs.push("world3");
  76425. }
  76426. // Get correct effect
  76427. var join = defines.join("\n");
  76428. if (this._cachedDefines !== join) {
  76429. this._cachedDefines = join;
  76430. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76431. }
  76432. return this._effect.isReady();
  76433. };
  76434. /**
  76435. * Gets the current underlying G Buffer.
  76436. * @returns the buffer
  76437. */
  76438. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76439. return this._multiRenderTarget;
  76440. };
  76441. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76442. /**
  76443. * Gets the number of samples used to render the buffer (anti aliasing).
  76444. */
  76445. get: function () {
  76446. return this._multiRenderTarget.samples;
  76447. },
  76448. /**
  76449. * Sets the number of samples used to render the buffer (anti aliasing).
  76450. */
  76451. set: function (value) {
  76452. this._multiRenderTarget.samples = value;
  76453. },
  76454. enumerable: true,
  76455. configurable: true
  76456. });
  76457. /**
  76458. * Disposes the renderer and frees up associated resources.
  76459. */
  76460. GeometryBufferRenderer.prototype.dispose = function () {
  76461. this.getGBuffer().dispose();
  76462. };
  76463. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76464. var _this = this;
  76465. var engine = this._scene.getEngine();
  76466. var count = this._enablePosition ? 3 : 2;
  76467. 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 });
  76468. if (!this.isSupported) {
  76469. return;
  76470. }
  76471. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76472. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76473. this._multiRenderTarget.refreshRate = 1;
  76474. this._multiRenderTarget.renderParticles = false;
  76475. this._multiRenderTarget.renderList = null;
  76476. // set default depth value to 1.0 (far away)
  76477. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76478. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76479. });
  76480. // Custom render function
  76481. var renderSubMesh = function (subMesh) {
  76482. var mesh = subMesh.getRenderingMesh();
  76483. var scene = _this._scene;
  76484. var engine = scene.getEngine();
  76485. var material = subMesh.getMaterial();
  76486. if (!material) {
  76487. return;
  76488. }
  76489. // Culling
  76490. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76491. // Managing instances
  76492. var batch = mesh._getInstancesRenderList(subMesh._id);
  76493. if (batch.mustReturn) {
  76494. return;
  76495. }
  76496. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76497. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76498. engine.enableEffect(_this._effect);
  76499. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76500. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76501. _this._effect.setMatrix("view", scene.getViewMatrix());
  76502. // Alpha test
  76503. if (material && material.needAlphaTesting()) {
  76504. var alphaTexture = material.getAlphaTestTexture();
  76505. if (alphaTexture) {
  76506. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76507. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76508. }
  76509. }
  76510. // Bones
  76511. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76512. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76513. }
  76514. // Draw
  76515. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76516. }
  76517. };
  76518. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76519. var index;
  76520. if (depthOnlySubMeshes.length) {
  76521. engine.setColorWrite(false);
  76522. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76523. renderSubMesh(depthOnlySubMeshes.data[index]);
  76524. }
  76525. engine.setColorWrite(true);
  76526. }
  76527. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76528. renderSubMesh(opaqueSubMeshes.data[index]);
  76529. }
  76530. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76531. renderSubMesh(alphaTestSubMeshes.data[index]);
  76532. }
  76533. };
  76534. };
  76535. return GeometryBufferRenderer;
  76536. }());
  76537. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76538. })(BABYLON || (BABYLON = {}));
  76539. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76540. var BABYLON;
  76541. (function (BABYLON) {
  76542. var RefractionPostProcess = /** @class */ (function (_super) {
  76543. __extends(RefractionPostProcess, _super);
  76544. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76545. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76546. _this.color = color;
  76547. _this.depth = depth;
  76548. _this.colorLevel = colorLevel;
  76549. _this._ownRefractionTexture = true;
  76550. _this.onActivateObservable.add(function (cam) {
  76551. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76552. });
  76553. _this.onApplyObservable.add(function (effect) {
  76554. effect.setColor3("baseColor", _this.color);
  76555. effect.setFloat("depth", _this.depth);
  76556. effect.setFloat("colorLevel", _this.colorLevel);
  76557. effect.setTexture("refractionSampler", _this._refTexture);
  76558. });
  76559. return _this;
  76560. }
  76561. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76562. /**
  76563. * Gets or sets the refraction texture
  76564. * Please note that you are responsible for disposing the texture if you set it manually
  76565. */
  76566. get: function () {
  76567. return this._refTexture;
  76568. },
  76569. set: function (value) {
  76570. if (this._refTexture && this._ownRefractionTexture) {
  76571. this._refTexture.dispose();
  76572. }
  76573. this._refTexture = value;
  76574. this._ownRefractionTexture = false;
  76575. },
  76576. enumerable: true,
  76577. configurable: true
  76578. });
  76579. // Methods
  76580. RefractionPostProcess.prototype.dispose = function (camera) {
  76581. if (this._refTexture && this._ownRefractionTexture) {
  76582. this._refTexture.dispose();
  76583. this._refTexture = null;
  76584. }
  76585. _super.prototype.dispose.call(this, camera);
  76586. };
  76587. return RefractionPostProcess;
  76588. }(BABYLON.PostProcess));
  76589. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76590. })(BABYLON || (BABYLON = {}));
  76591. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76592. var BABYLON;
  76593. (function (BABYLON) {
  76594. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76595. __extends(BlackAndWhitePostProcess, _super);
  76596. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76597. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76598. _this.degree = 1;
  76599. _this.onApplyObservable.add(function (effect) {
  76600. effect.setFloat("degree", _this.degree);
  76601. });
  76602. return _this;
  76603. }
  76604. return BlackAndWhitePostProcess;
  76605. }(BABYLON.PostProcess));
  76606. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76607. })(BABYLON || (BABYLON = {}));
  76608. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76609. var BABYLON;
  76610. (function (BABYLON) {
  76611. /**
  76612. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76613. * input texture to perform effects such as edge detection or sharpening
  76614. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76615. */
  76616. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76617. __extends(ConvolutionPostProcess, _super);
  76618. /**
  76619. * Creates a new instance ConvolutionPostProcess
  76620. * @param name The name of the effect.
  76621. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76622. * @param options The required width/height ratio to downsize to before computing the render pass.
  76623. * @param camera The camera to apply the render pass to.
  76624. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76625. * @param engine The engine which the post process will be applied. (default: current engine)
  76626. * @param reusable If the post process can be reused on the same frame. (default: false)
  76627. * @param textureType Type of textures used when performing the post process. (default: 0)
  76628. */
  76629. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76630. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76631. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76632. _this.kernel = kernel;
  76633. _this.onApply = function (effect) {
  76634. effect.setFloat2("screenSize", _this.width, _this.height);
  76635. effect.setArray("kernel", _this.kernel);
  76636. };
  76637. return _this;
  76638. }
  76639. // Statics
  76640. /**
  76641. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76642. */
  76643. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76644. /**
  76645. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76646. */
  76647. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76648. /**
  76649. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76650. */
  76651. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76652. /**
  76653. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76654. */
  76655. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76656. /**
  76657. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76658. */
  76659. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76660. /**
  76661. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76662. */
  76663. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76664. return ConvolutionPostProcess;
  76665. }(BABYLON.PostProcess));
  76666. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76667. })(BABYLON || (BABYLON = {}));
  76668. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76669. var BABYLON;
  76670. (function (BABYLON) {
  76671. var FilterPostProcess = /** @class */ (function (_super) {
  76672. __extends(FilterPostProcess, _super);
  76673. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76674. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76675. _this.kernelMatrix = kernelMatrix;
  76676. _this.onApply = function (effect) {
  76677. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76678. };
  76679. return _this;
  76680. }
  76681. return FilterPostProcess;
  76682. }(BABYLON.PostProcess));
  76683. BABYLON.FilterPostProcess = FilterPostProcess;
  76684. })(BABYLON || (BABYLON = {}));
  76685. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76686. var BABYLON;
  76687. (function (BABYLON) {
  76688. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76689. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76690. __extends(VolumetricLightScatteringPostProcess, _super);
  76691. /**
  76692. * @constructor
  76693. * @param {string} name - The post-process name
  76694. * @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)
  76695. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76696. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76697. * @param {number} samples - The post-process quality, default 100
  76698. * @param {number} samplingMode - The post-process filtering mode
  76699. * @param {BABYLON.Engine} engine - The babylon engine
  76700. * @param {boolean} reusable - If the post-process is reusable
  76701. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76702. */
  76703. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76704. if (samples === void 0) { samples = 100; }
  76705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76706. 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;
  76707. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76708. /**
  76709. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76710. */
  76711. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76712. /**
  76713. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76714. */
  76715. _this.useCustomMeshPosition = false;
  76716. /**
  76717. * If the post-process should inverse the light scattering direction
  76718. */
  76719. _this.invert = true;
  76720. /**
  76721. * Array containing the excluded meshes not rendered in the internal pass
  76722. */
  76723. _this.excludedMeshes = new Array();
  76724. /**
  76725. * Controls the overall intensity of the post-process
  76726. */
  76727. _this.exposure = 0.3;
  76728. /**
  76729. * Dissipates each sample's contribution in range [0, 1]
  76730. */
  76731. _this.decay = 0.96815;
  76732. /**
  76733. * Controls the overall intensity of each sample
  76734. */
  76735. _this.weight = 0.58767;
  76736. /**
  76737. * Controls the density of each sample
  76738. */
  76739. _this.density = 0.926;
  76740. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76741. engine = scene.getEngine();
  76742. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76743. // Configure mesh
  76744. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76745. // Configure
  76746. _this._createPass(scene, ratio.passRatio || ratio);
  76747. _this.onActivate = function (camera) {
  76748. if (!_this.isSupported) {
  76749. _this.dispose(camera);
  76750. }
  76751. _this.onActivate = null;
  76752. };
  76753. _this.onApplyObservable.add(function (effect) {
  76754. _this._updateMeshScreenCoordinates(scene);
  76755. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76756. effect.setFloat("exposure", _this.exposure);
  76757. effect.setFloat("decay", _this.decay);
  76758. effect.setFloat("weight", _this.weight);
  76759. effect.setFloat("density", _this.density);
  76760. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76761. });
  76762. return _this;
  76763. }
  76764. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76765. get: function () {
  76766. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76767. return false;
  76768. },
  76769. set: function (useDiffuseColor) {
  76770. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76771. },
  76772. enumerable: true,
  76773. configurable: true
  76774. });
  76775. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76776. return "VolumetricLightScatteringPostProcess";
  76777. };
  76778. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76779. var mesh = subMesh.getMesh();
  76780. // Render this.mesh as default
  76781. if (mesh === this.mesh && mesh.material) {
  76782. return mesh.material.isReady(mesh);
  76783. }
  76784. var defines = [];
  76785. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76786. var material = subMesh.getMaterial();
  76787. // Alpha test
  76788. if (material) {
  76789. if (material.needAlphaTesting()) {
  76790. defines.push("#define ALPHATEST");
  76791. }
  76792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76793. attribs.push(BABYLON.VertexBuffer.UVKind);
  76794. defines.push("#define UV1");
  76795. }
  76796. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76797. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76798. defines.push("#define UV2");
  76799. }
  76800. }
  76801. // Bones
  76802. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76803. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76804. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76805. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76806. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76807. }
  76808. else {
  76809. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76810. }
  76811. // Instances
  76812. if (useInstances) {
  76813. defines.push("#define INSTANCES");
  76814. attribs.push("world0");
  76815. attribs.push("world1");
  76816. attribs.push("world2");
  76817. attribs.push("world3");
  76818. }
  76819. // Get correct effect
  76820. var join = defines.join("\n");
  76821. if (this._cachedDefines !== join) {
  76822. this._cachedDefines = join;
  76823. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76824. }
  76825. return this._volumetricLightScatteringPass.isReady();
  76826. };
  76827. /**
  76828. * Sets the new light position for light scattering effect
  76829. * @param {BABYLON.Vector3} The new custom light position
  76830. */
  76831. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76832. this.customMeshPosition = position;
  76833. };
  76834. /**
  76835. * Returns the light position for light scattering effect
  76836. * @return {BABYLON.Vector3} The custom light position
  76837. */
  76838. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76839. return this.customMeshPosition;
  76840. };
  76841. /**
  76842. * Disposes the internal assets and detaches the post-process from the camera
  76843. */
  76844. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76845. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76846. if (rttIndex !== -1) {
  76847. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76848. }
  76849. this._volumetricLightScatteringRTT.dispose();
  76850. _super.prototype.dispose.call(this, camera);
  76851. };
  76852. /**
  76853. * Returns the render target texture used by the post-process
  76854. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76855. */
  76856. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76857. return this._volumetricLightScatteringRTT;
  76858. };
  76859. // Private methods
  76860. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76861. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76862. return true;
  76863. }
  76864. return false;
  76865. };
  76866. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76867. var _this = this;
  76868. var engine = scene.getEngine();
  76869. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76870. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76871. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76872. this._volumetricLightScatteringRTT.renderList = null;
  76873. this._volumetricLightScatteringRTT.renderParticles = false;
  76874. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76875. var camera = this.getCamera();
  76876. if (camera) {
  76877. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76878. }
  76879. else {
  76880. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76881. }
  76882. // Custom render function for submeshes
  76883. var renderSubMesh = function (subMesh) {
  76884. var mesh = subMesh.getRenderingMesh();
  76885. if (_this._meshExcluded(mesh)) {
  76886. return;
  76887. }
  76888. var material = subMesh.getMaterial();
  76889. if (!material) {
  76890. return;
  76891. }
  76892. var scene = mesh.getScene();
  76893. var engine = scene.getEngine();
  76894. // Culling
  76895. engine.setState(material.backFaceCulling);
  76896. // Managing instances
  76897. var batch = mesh._getInstancesRenderList(subMesh._id);
  76898. if (batch.mustReturn) {
  76899. return;
  76900. }
  76901. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76902. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76903. var effect = _this._volumetricLightScatteringPass;
  76904. if (mesh === _this.mesh) {
  76905. if (subMesh.effect) {
  76906. effect = subMesh.effect;
  76907. }
  76908. else {
  76909. effect = material.getEffect();
  76910. }
  76911. }
  76912. engine.enableEffect(effect);
  76913. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76914. if (mesh === _this.mesh) {
  76915. material.bind(mesh.getWorldMatrix(), mesh);
  76916. }
  76917. else {
  76918. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76919. // Alpha test
  76920. if (material && material.needAlphaTesting()) {
  76921. var alphaTexture = material.getAlphaTestTexture();
  76922. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76923. if (alphaTexture) {
  76924. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76925. }
  76926. }
  76927. // Bones
  76928. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76929. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76930. }
  76931. }
  76932. // Draw
  76933. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76934. }
  76935. };
  76936. // Render target texture callbacks
  76937. var savedSceneClearColor;
  76938. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76939. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76940. savedSceneClearColor = scene.clearColor;
  76941. scene.clearColor = sceneClearColor;
  76942. });
  76943. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76944. scene.clearColor = savedSceneClearColor;
  76945. });
  76946. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76947. var engine = scene.getEngine();
  76948. var index;
  76949. if (depthOnlySubMeshes.length) {
  76950. engine.setColorWrite(false);
  76951. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76952. renderSubMesh(depthOnlySubMeshes.data[index]);
  76953. }
  76954. engine.setColorWrite(true);
  76955. }
  76956. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76957. renderSubMesh(opaqueSubMeshes.data[index]);
  76958. }
  76959. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76960. renderSubMesh(alphaTestSubMeshes.data[index]);
  76961. }
  76962. if (transparentSubMeshes.length) {
  76963. // Sort sub meshes
  76964. for (index = 0; index < transparentSubMeshes.length; index++) {
  76965. var submesh = transparentSubMeshes.data[index];
  76966. var boundingInfo = submesh.getBoundingInfo();
  76967. if (boundingInfo && scene.activeCamera) {
  76968. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76969. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76970. }
  76971. }
  76972. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76973. sortedArray.sort(function (a, b) {
  76974. // Alpha index first
  76975. if (a._alphaIndex > b._alphaIndex) {
  76976. return 1;
  76977. }
  76978. if (a._alphaIndex < b._alphaIndex) {
  76979. return -1;
  76980. }
  76981. // Then distance to camera
  76982. if (a._distanceToCamera < b._distanceToCamera) {
  76983. return 1;
  76984. }
  76985. if (a._distanceToCamera > b._distanceToCamera) {
  76986. return -1;
  76987. }
  76988. return 0;
  76989. });
  76990. // Render sub meshes
  76991. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76992. for (index = 0; index < sortedArray.length; index++) {
  76993. renderSubMesh(sortedArray[index]);
  76994. }
  76995. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76996. }
  76997. };
  76998. };
  76999. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77000. var transform = scene.getTransformMatrix();
  77001. var meshPosition;
  77002. if (this.useCustomMeshPosition) {
  77003. meshPosition = this.customMeshPosition;
  77004. }
  77005. else if (this.attachedNode) {
  77006. meshPosition = this.attachedNode.position;
  77007. }
  77008. else {
  77009. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77010. }
  77011. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77012. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77013. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77014. if (this.invert)
  77015. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77016. };
  77017. // Static methods
  77018. /**
  77019. * Creates a default mesh for the Volumeric Light Scattering post-process
  77020. * @param {string} The mesh name
  77021. * @param {BABYLON.Scene} The scene where to create the mesh
  77022. * @return {BABYLON.Mesh} the default mesh
  77023. */
  77024. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77025. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77026. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77027. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77028. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77029. mesh.material = material;
  77030. return mesh;
  77031. };
  77032. __decorate([
  77033. BABYLON.serializeAsVector3()
  77034. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77035. __decorate([
  77036. BABYLON.serialize()
  77037. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77038. __decorate([
  77039. BABYLON.serialize()
  77040. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77041. __decorate([
  77042. BABYLON.serializeAsMeshReference()
  77043. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77044. __decorate([
  77045. BABYLON.serialize()
  77046. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77047. __decorate([
  77048. BABYLON.serialize()
  77049. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77050. __decorate([
  77051. BABYLON.serialize()
  77052. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77053. __decorate([
  77054. BABYLON.serialize()
  77055. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77056. __decorate([
  77057. BABYLON.serialize()
  77058. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77059. return VolumetricLightScatteringPostProcess;
  77060. }(BABYLON.PostProcess));
  77061. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77062. })(BABYLON || (BABYLON = {}));
  77063. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77064. //
  77065. // This post-process allows the modification of rendered colors by using
  77066. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77067. //
  77068. // The object needs to be provided an url to a texture containing the color
  77069. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77070. // Use an image editing software to tweak the LUT to match your needs.
  77071. //
  77072. // For an example of a color LUT, see here:
  77073. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77074. // For explanations on color grading, see here:
  77075. // http://udn.epicgames.com/Three/ColorGrading.html
  77076. //
  77077. var BABYLON;
  77078. (function (BABYLON) {
  77079. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77080. __extends(ColorCorrectionPostProcess, _super);
  77081. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77082. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77083. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77084. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77085. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77086. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77087. _this.onApply = function (effect) {
  77088. effect.setTexture("colorTable", _this._colorTableTexture);
  77089. };
  77090. return _this;
  77091. }
  77092. return ColorCorrectionPostProcess;
  77093. }(BABYLON.PostProcess));
  77094. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77095. })(BABYLON || (BABYLON = {}));
  77096. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77097. var BABYLON;
  77098. (function (BABYLON) {
  77099. /** Defines operator used for tonemapping */
  77100. var TonemappingOperator;
  77101. (function (TonemappingOperator) {
  77102. /** Hable */
  77103. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77104. /** Reinhard */
  77105. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77106. /** HejiDawson */
  77107. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77108. /** Photographic */
  77109. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77110. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77111. ;
  77112. /**
  77113. * Defines a post process to apply tone mapping
  77114. */
  77115. var TonemapPostProcess = /** @class */ (function (_super) {
  77116. __extends(TonemapPostProcess, _super);
  77117. /**
  77118. * Creates a new TonemapPostProcess
  77119. * @param name defines the name of the postprocess
  77120. * @param _operator defines the operator to use
  77121. * @param exposureAdjustment defines the required exposure adjustement
  77122. * @param camera defines the camera to use (can be null)
  77123. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77124. * @param engine defines the hosting engine (can be ignore if camera is set)
  77125. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77126. */
  77127. function TonemapPostProcess(name, _operator,
  77128. /** Defines the required exposure adjustement */
  77129. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77130. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77131. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77132. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77133. _this._operator = _operator;
  77134. _this.exposureAdjustment = exposureAdjustment;
  77135. var defines = "#define ";
  77136. if (_this._operator === TonemappingOperator.Hable)
  77137. defines += "HABLE_TONEMAPPING";
  77138. else if (_this._operator === TonemappingOperator.Reinhard)
  77139. defines += "REINHARD_TONEMAPPING";
  77140. else if (_this._operator === TonemappingOperator.HejiDawson)
  77141. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77142. else if (_this._operator === TonemappingOperator.Photographic)
  77143. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77144. //sadly a second call to create the effect.
  77145. _this.updateEffect(defines);
  77146. _this.onApply = function (effect) {
  77147. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77148. };
  77149. return _this;
  77150. }
  77151. return TonemapPostProcess;
  77152. }(BABYLON.PostProcess));
  77153. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77154. })(BABYLON || (BABYLON = {}));
  77155. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77156. var BABYLON;
  77157. (function (BABYLON) {
  77158. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77159. __extends(DisplayPassPostProcess, _super);
  77160. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77161. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77162. }
  77163. return DisplayPassPostProcess;
  77164. }(BABYLON.PostProcess));
  77165. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77166. })(BABYLON || (BABYLON = {}));
  77167. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77168. var BABYLON;
  77169. (function (BABYLON) {
  77170. var HighlightsPostProcess = /** @class */ (function (_super) {
  77171. __extends(HighlightsPostProcess, _super);
  77172. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77173. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77174. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77175. }
  77176. return HighlightsPostProcess;
  77177. }(BABYLON.PostProcess));
  77178. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77179. })(BABYLON || (BABYLON = {}));
  77180. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77181. var BABYLON;
  77182. (function (BABYLON) {
  77183. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77184. __extends(ImageProcessingPostProcess, _super);
  77185. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77186. if (camera === void 0) { camera = null; }
  77187. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77188. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77189. _this._fromLinearSpace = true;
  77190. /**
  77191. * Defines cache preventing GC.
  77192. */
  77193. _this._defines = {
  77194. IMAGEPROCESSING: false,
  77195. VIGNETTE: false,
  77196. VIGNETTEBLENDMODEMULTIPLY: false,
  77197. VIGNETTEBLENDMODEOPAQUE: false,
  77198. TONEMAPPING: false,
  77199. CONTRAST: false,
  77200. COLORCURVES: false,
  77201. COLORGRADING: false,
  77202. COLORGRADING3D: false,
  77203. FROMLINEARSPACE: false,
  77204. SAMPLER3DGREENDEPTH: false,
  77205. SAMPLER3DBGRMAP: false,
  77206. IMAGEPROCESSINGPOSTPROCESS: false,
  77207. EXPOSURE: false,
  77208. };
  77209. // Setup the configuration as forced by the constructor. This would then not force the
  77210. // scene materials output in linear space and let untouched the default forward pass.
  77211. if (imageProcessingConfiguration) {
  77212. imageProcessingConfiguration.applyByPostProcess = true;
  77213. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77214. // This will cause the shader to be compiled
  77215. _this.fromLinearSpace = false;
  77216. }
  77217. // Setup the default processing configuration to the scene.
  77218. else {
  77219. _this._attachImageProcessingConfiguration(null, true);
  77220. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77221. }
  77222. _this.onApply = function (effect) {
  77223. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77224. };
  77225. return _this;
  77226. }
  77227. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77228. /**
  77229. * Gets the image processing configuration used either in this material.
  77230. */
  77231. get: function () {
  77232. return this._imageProcessingConfiguration;
  77233. },
  77234. /**
  77235. * Sets the Default image processing configuration used either in the this material.
  77236. *
  77237. * If sets to null, the scene one is in use.
  77238. */
  77239. set: function (value) {
  77240. this._attachImageProcessingConfiguration(value);
  77241. },
  77242. enumerable: true,
  77243. configurable: true
  77244. });
  77245. /**
  77246. * Attaches a new image processing configuration to the PBR Material.
  77247. * @param configuration
  77248. */
  77249. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77250. var _this = this;
  77251. if (doNotBuild === void 0) { doNotBuild = false; }
  77252. if (configuration === this._imageProcessingConfiguration) {
  77253. return;
  77254. }
  77255. // Detaches observer.
  77256. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77257. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77258. }
  77259. // Pick the scene configuration if needed.
  77260. if (!configuration) {
  77261. var scene = null;
  77262. var engine = this.getEngine();
  77263. var camera = this.getCamera();
  77264. if (camera) {
  77265. scene = camera.getScene();
  77266. }
  77267. else if (engine && engine.scenes) {
  77268. var scenes = engine.scenes;
  77269. scene = scenes[scenes.length - 1];
  77270. }
  77271. else {
  77272. scene = BABYLON.Engine.LastCreatedScene;
  77273. }
  77274. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77275. }
  77276. else {
  77277. this._imageProcessingConfiguration = configuration;
  77278. }
  77279. // Attaches observer.
  77280. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77281. _this._updateParameters();
  77282. });
  77283. // Ensure the effect will be rebuilt.
  77284. if (!doNotBuild) {
  77285. this._updateParameters();
  77286. }
  77287. };
  77288. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77289. /**
  77290. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77291. */
  77292. get: function () {
  77293. return this.imageProcessingConfiguration.colorCurves;
  77294. },
  77295. /**
  77296. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77297. */
  77298. set: function (value) {
  77299. this.imageProcessingConfiguration.colorCurves = value;
  77300. },
  77301. enumerable: true,
  77302. configurable: true
  77303. });
  77304. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77305. /**
  77306. * Gets wether the color curves effect is enabled.
  77307. */
  77308. get: function () {
  77309. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77310. },
  77311. /**
  77312. * Sets wether the color curves effect is enabled.
  77313. */
  77314. set: function (value) {
  77315. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77316. },
  77317. enumerable: true,
  77318. configurable: true
  77319. });
  77320. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77321. /**
  77322. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77323. */
  77324. get: function () {
  77325. return this.imageProcessingConfiguration.colorGradingTexture;
  77326. },
  77327. /**
  77328. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77329. */
  77330. set: function (value) {
  77331. this.imageProcessingConfiguration.colorGradingTexture = value;
  77332. },
  77333. enumerable: true,
  77334. configurable: true
  77335. });
  77336. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77337. /**
  77338. * Gets wether the color grading effect is enabled.
  77339. */
  77340. get: function () {
  77341. return this.imageProcessingConfiguration.colorGradingEnabled;
  77342. },
  77343. /**
  77344. * Gets wether the color grading effect is enabled.
  77345. */
  77346. set: function (value) {
  77347. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77348. },
  77349. enumerable: true,
  77350. configurable: true
  77351. });
  77352. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77353. /**
  77354. * Gets exposure used in the effect.
  77355. */
  77356. get: function () {
  77357. return this.imageProcessingConfiguration.exposure;
  77358. },
  77359. /**
  77360. * Sets exposure used in the effect.
  77361. */
  77362. set: function (value) {
  77363. this.imageProcessingConfiguration.exposure = value;
  77364. },
  77365. enumerable: true,
  77366. configurable: true
  77367. });
  77368. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77369. /**
  77370. * Gets wether tonemapping is enabled or not.
  77371. */
  77372. get: function () {
  77373. return this._imageProcessingConfiguration.toneMappingEnabled;
  77374. },
  77375. /**
  77376. * Sets wether tonemapping is enabled or not
  77377. */
  77378. set: function (value) {
  77379. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77380. },
  77381. enumerable: true,
  77382. configurable: true
  77383. });
  77384. ;
  77385. ;
  77386. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77387. /**
  77388. * Gets contrast used in the effect.
  77389. */
  77390. get: function () {
  77391. return this.imageProcessingConfiguration.contrast;
  77392. },
  77393. /**
  77394. * Sets contrast used in the effect.
  77395. */
  77396. set: function (value) {
  77397. this.imageProcessingConfiguration.contrast = value;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77403. /**
  77404. * Gets Vignette stretch size.
  77405. */
  77406. get: function () {
  77407. return this.imageProcessingConfiguration.vignetteStretch;
  77408. },
  77409. /**
  77410. * Sets Vignette stretch size.
  77411. */
  77412. set: function (value) {
  77413. this.imageProcessingConfiguration.vignetteStretch = value;
  77414. },
  77415. enumerable: true,
  77416. configurable: true
  77417. });
  77418. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77419. /**
  77420. * Gets Vignette centre X Offset.
  77421. */
  77422. get: function () {
  77423. return this.imageProcessingConfiguration.vignetteCentreX;
  77424. },
  77425. /**
  77426. * Sets Vignette centre X Offset.
  77427. */
  77428. set: function (value) {
  77429. this.imageProcessingConfiguration.vignetteCentreX = value;
  77430. },
  77431. enumerable: true,
  77432. configurable: true
  77433. });
  77434. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77435. /**
  77436. * Gets Vignette centre Y Offset.
  77437. */
  77438. get: function () {
  77439. return this.imageProcessingConfiguration.vignetteCentreY;
  77440. },
  77441. /**
  77442. * Sets Vignette centre Y Offset.
  77443. */
  77444. set: function (value) {
  77445. this.imageProcessingConfiguration.vignetteCentreY = value;
  77446. },
  77447. enumerable: true,
  77448. configurable: true
  77449. });
  77450. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77451. /**
  77452. * Gets Vignette weight or intensity of the vignette effect.
  77453. */
  77454. get: function () {
  77455. return this.imageProcessingConfiguration.vignetteWeight;
  77456. },
  77457. /**
  77458. * Sets Vignette weight or intensity of the vignette effect.
  77459. */
  77460. set: function (value) {
  77461. this.imageProcessingConfiguration.vignetteWeight = value;
  77462. },
  77463. enumerable: true,
  77464. configurable: true
  77465. });
  77466. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77467. /**
  77468. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77469. * if vignetteEnabled is set to true.
  77470. */
  77471. get: function () {
  77472. return this.imageProcessingConfiguration.vignetteColor;
  77473. },
  77474. /**
  77475. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77476. * if vignetteEnabled is set to true.
  77477. */
  77478. set: function (value) {
  77479. this.imageProcessingConfiguration.vignetteColor = value;
  77480. },
  77481. enumerable: true,
  77482. configurable: true
  77483. });
  77484. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77485. /**
  77486. * Gets Camera field of view used by the Vignette effect.
  77487. */
  77488. get: function () {
  77489. return this.imageProcessingConfiguration.vignetteCameraFov;
  77490. },
  77491. /**
  77492. * Sets Camera field of view used by the Vignette effect.
  77493. */
  77494. set: function (value) {
  77495. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77496. },
  77497. enumerable: true,
  77498. configurable: true
  77499. });
  77500. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77501. /**
  77502. * Gets the vignette blend mode allowing different kind of effect.
  77503. */
  77504. get: function () {
  77505. return this.imageProcessingConfiguration.vignetteBlendMode;
  77506. },
  77507. /**
  77508. * Sets the vignette blend mode allowing different kind of effect.
  77509. */
  77510. set: function (value) {
  77511. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77512. },
  77513. enumerable: true,
  77514. configurable: true
  77515. });
  77516. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77517. /**
  77518. * Gets wether the vignette effect is enabled.
  77519. */
  77520. get: function () {
  77521. return this.imageProcessingConfiguration.vignetteEnabled;
  77522. },
  77523. /**
  77524. * Sets wether the vignette effect is enabled.
  77525. */
  77526. set: function (value) {
  77527. this.imageProcessingConfiguration.vignetteEnabled = value;
  77528. },
  77529. enumerable: true,
  77530. configurable: true
  77531. });
  77532. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77533. /**
  77534. * Gets wether the input of the processing is in Gamma or Linear Space.
  77535. */
  77536. get: function () {
  77537. return this._fromLinearSpace;
  77538. },
  77539. /**
  77540. * Sets wether the input of the processing is in Gamma or Linear Space.
  77541. */
  77542. set: function (value) {
  77543. if (this._fromLinearSpace === value) {
  77544. return;
  77545. }
  77546. this._fromLinearSpace = value;
  77547. this._updateParameters();
  77548. },
  77549. enumerable: true,
  77550. configurable: true
  77551. });
  77552. ImageProcessingPostProcess.prototype.getClassName = function () {
  77553. return "ImageProcessingPostProcess";
  77554. };
  77555. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77556. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77557. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77558. var defines = "";
  77559. for (var define in this._defines) {
  77560. if (this._defines[define]) {
  77561. defines += "#define " + define + ";\r\n";
  77562. }
  77563. }
  77564. var samplers = ["textureSampler"];
  77565. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77566. var uniforms = ["scale"];
  77567. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77568. this.updateEffect(defines, uniforms, samplers);
  77569. };
  77570. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77571. _super.prototype.dispose.call(this, camera);
  77572. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77573. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77574. }
  77575. this.imageProcessingConfiguration.applyByPostProcess = false;
  77576. };
  77577. __decorate([
  77578. BABYLON.serialize()
  77579. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77580. return ImageProcessingPostProcess;
  77581. }(BABYLON.PostProcess));
  77582. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77583. })(BABYLON || (BABYLON = {}));
  77584. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77585. var BABYLON;
  77586. (function (BABYLON) {
  77587. /**
  77588. * Class used to store bone information
  77589. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77590. */
  77591. var Bone = /** @class */ (function (_super) {
  77592. __extends(Bone, _super);
  77593. /**
  77594. * Create a new bone
  77595. * @param name defines the bone name
  77596. * @param skeleton defines the parent skeleton
  77597. * @param parentBone defines the parent (can be null if the bone is the root)
  77598. * @param localMatrix defines the local matrix
  77599. * @param restPose defines the rest pose matrix
  77600. * @param baseMatrix defines the base matrix
  77601. * @param index defines index of the bone in the hiearchy
  77602. */
  77603. function Bone(
  77604. /**
  77605. * defines the bone name
  77606. */
  77607. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77608. if (parentBone === void 0) { parentBone = null; }
  77609. if (localMatrix === void 0) { localMatrix = null; }
  77610. if (restPose === void 0) { restPose = null; }
  77611. if (baseMatrix === void 0) { baseMatrix = null; }
  77612. if (index === void 0) { index = null; }
  77613. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77614. _this.name = name;
  77615. /**
  77616. * Gets the list of child bones
  77617. */
  77618. _this.children = new Array();
  77619. /** Gets the animations associated with this bone */
  77620. _this.animations = new Array();
  77621. /**
  77622. * @hidden Internal only
  77623. * Set this value to map this bone to a different index in the transform matrices
  77624. * Set this value to -1 to exclude the bone from the transform matrices
  77625. */
  77626. _this._index = null;
  77627. _this._absoluteTransform = new BABYLON.Matrix();
  77628. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77629. _this._scalingDeterminant = 1;
  77630. _this._worldTransform = new BABYLON.Matrix();
  77631. _this._needToDecompose = true;
  77632. _this._needToCompose = false;
  77633. _this._skeleton = skeleton;
  77634. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77635. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77636. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77637. _this._index = index;
  77638. skeleton.bones.push(_this);
  77639. _this.setParent(parentBone, false);
  77640. if (baseMatrix || localMatrix) {
  77641. _this._updateDifferenceMatrix();
  77642. }
  77643. return _this;
  77644. }
  77645. Object.defineProperty(Bone.prototype, "_matrix", {
  77646. /** @hidden */
  77647. get: function () {
  77648. this._compose();
  77649. return this._localMatrix;
  77650. },
  77651. /** @hidden */
  77652. set: function (value) {
  77653. this._localMatrix.copyFrom(value);
  77654. this._needToDecompose = true;
  77655. },
  77656. enumerable: true,
  77657. configurable: true
  77658. });
  77659. // Members
  77660. /**
  77661. * Gets the parent skeleton
  77662. * @returns a skeleton
  77663. */
  77664. Bone.prototype.getSkeleton = function () {
  77665. return this._skeleton;
  77666. };
  77667. /**
  77668. * Gets parent bone
  77669. * @returns a bone or null if the bone is the root of the bone hierarchy
  77670. */
  77671. Bone.prototype.getParent = function () {
  77672. return this._parent;
  77673. };
  77674. /**
  77675. * Sets the parent bone
  77676. * @param parent defines the parent (can be null if the bone is the root)
  77677. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77678. */
  77679. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77680. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77681. if (this._parent === parent) {
  77682. return;
  77683. }
  77684. if (this._parent) {
  77685. var index = this._parent.children.indexOf(this);
  77686. if (index !== -1) {
  77687. this._parent.children.splice(index, 1);
  77688. }
  77689. }
  77690. this._parent = parent;
  77691. if (this._parent) {
  77692. this._parent.children.push(this);
  77693. }
  77694. if (updateDifferenceMatrix) {
  77695. this._updateDifferenceMatrix();
  77696. }
  77697. this.markAsDirty();
  77698. };
  77699. /**
  77700. * Gets the local matrix
  77701. * @returns a matrix
  77702. */
  77703. Bone.prototype.getLocalMatrix = function () {
  77704. this._compose();
  77705. return this._localMatrix;
  77706. };
  77707. /**
  77708. * Gets the base matrix (initial matrix which remains unchanged)
  77709. * @returns a matrix
  77710. */
  77711. Bone.prototype.getBaseMatrix = function () {
  77712. return this._baseMatrix;
  77713. };
  77714. /**
  77715. * Gets the rest pose matrix
  77716. * @returns a matrix
  77717. */
  77718. Bone.prototype.getRestPose = function () {
  77719. return this._restPose;
  77720. };
  77721. /**
  77722. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77723. */
  77724. Bone.prototype.getWorldMatrix = function () {
  77725. return this._worldTransform;
  77726. };
  77727. /**
  77728. * Sets the local matrix to rest pose matrix
  77729. */
  77730. Bone.prototype.returnToRest = function () {
  77731. this.updateMatrix(this._restPose.clone());
  77732. };
  77733. /**
  77734. * Gets the inverse of the absolute transform matrix.
  77735. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77736. * @returns a matrix
  77737. */
  77738. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77739. return this._invertedAbsoluteTransform;
  77740. };
  77741. /**
  77742. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77743. * @returns a matrix
  77744. */
  77745. Bone.prototype.getAbsoluteTransform = function () {
  77746. return this._absoluteTransform;
  77747. };
  77748. Object.defineProperty(Bone.prototype, "position", {
  77749. // Properties (matches AbstractMesh properties)
  77750. /** Gets or sets current position (in local space) */
  77751. get: function () {
  77752. this._decompose();
  77753. return this._localPosition;
  77754. },
  77755. set: function (newPosition) {
  77756. this._decompose();
  77757. this._localPosition.copyFrom(newPosition);
  77758. this._markAsDirtyAndCompose();
  77759. },
  77760. enumerable: true,
  77761. configurable: true
  77762. });
  77763. Object.defineProperty(Bone.prototype, "rotation", {
  77764. /** Gets or sets current rotation (in local space) */
  77765. get: function () {
  77766. return this.getRotation();
  77767. },
  77768. set: function (newRotation) {
  77769. this.setRotation(newRotation);
  77770. },
  77771. enumerable: true,
  77772. configurable: true
  77773. });
  77774. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77775. /** Gets or sets current rotation quaternion (in local space) */
  77776. get: function () {
  77777. this._decompose();
  77778. return this._localRotation;
  77779. },
  77780. set: function (newRotation) {
  77781. this.setRotationQuaternion(newRotation);
  77782. },
  77783. enumerable: true,
  77784. configurable: true
  77785. });
  77786. Object.defineProperty(Bone.prototype, "scaling", {
  77787. /** Gets or sets current scaling (in local space) */
  77788. get: function () {
  77789. return this.getScale();
  77790. },
  77791. set: function (newScaling) {
  77792. this.setScale(newScaling);
  77793. },
  77794. enumerable: true,
  77795. configurable: true
  77796. });
  77797. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77798. /**
  77799. * Gets the animation properties override
  77800. */
  77801. get: function () {
  77802. return this._skeleton.animationPropertiesOverride;
  77803. },
  77804. enumerable: true,
  77805. configurable: true
  77806. });
  77807. // Methods
  77808. Bone.prototype._decompose = function () {
  77809. if (!this._needToDecompose) {
  77810. return;
  77811. }
  77812. this._needToDecompose = false;
  77813. if (!this._localScaling) {
  77814. this._localScaling = BABYLON.Vector3.Zero();
  77815. this._localRotation = BABYLON.Quaternion.Zero();
  77816. this._localPosition = BABYLON.Vector3.Zero();
  77817. }
  77818. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77819. };
  77820. Bone.prototype._compose = function () {
  77821. if (!this._needToCompose) {
  77822. return;
  77823. }
  77824. this._needToCompose = false;
  77825. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77826. };
  77827. /**
  77828. * Update the base and local matrices
  77829. * @param matrix defines the new base or local matrix
  77830. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77831. * @param updateLocalMatrix defines if the local matrix should be updated
  77832. */
  77833. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77834. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77835. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77836. this._baseMatrix.copyFrom(matrix);
  77837. if (updateDifferenceMatrix) {
  77838. this._updateDifferenceMatrix();
  77839. }
  77840. if (updateLocalMatrix) {
  77841. this._localMatrix.copyFrom(matrix);
  77842. this._markAsDirtyAndDecompose();
  77843. }
  77844. else {
  77845. this.markAsDirty();
  77846. }
  77847. };
  77848. /** @hidden */
  77849. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77850. if (updateChildren === void 0) { updateChildren = true; }
  77851. if (!rootMatrix) {
  77852. rootMatrix = this._baseMatrix;
  77853. }
  77854. if (this._parent) {
  77855. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77856. }
  77857. else {
  77858. this._absoluteTransform.copyFrom(rootMatrix);
  77859. }
  77860. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77861. if (updateChildren) {
  77862. for (var index = 0; index < this.children.length; index++) {
  77863. this.children[index]._updateDifferenceMatrix();
  77864. }
  77865. }
  77866. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77867. };
  77868. /**
  77869. * Flag the bone as dirty (Forcing it to update everything)
  77870. */
  77871. Bone.prototype.markAsDirty = function () {
  77872. this._currentRenderId++;
  77873. this._childRenderId++;
  77874. this._skeleton._markAsDirty();
  77875. };
  77876. Bone.prototype._markAsDirtyAndCompose = function () {
  77877. this.markAsDirty();
  77878. this._needToCompose = true;
  77879. };
  77880. Bone.prototype._markAsDirtyAndDecompose = function () {
  77881. this.markAsDirty();
  77882. this._needToDecompose = true;
  77883. };
  77884. /**
  77885. * Copy an animation range from another bone
  77886. * @param source defines the source bone
  77887. * @param rangeName defines the range name to copy
  77888. * @param frameOffset defines the frame offset
  77889. * @param rescaleAsRequired defines if rescaling must be applied if required
  77890. * @param skelDimensionsRatio defines the scaling ratio
  77891. * @returns true if operation was successful
  77892. */
  77893. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77894. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77895. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77896. // all animation may be coming from a library skeleton, so may need to create animation
  77897. if (this.animations.length === 0) {
  77898. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77899. this.animations[0].setKeys([]);
  77900. }
  77901. // get animation info / verify there is such a range from the source bone
  77902. var sourceRange = source.animations[0].getRange(rangeName);
  77903. if (!sourceRange) {
  77904. return false;
  77905. }
  77906. var from = sourceRange.from;
  77907. var to = sourceRange.to;
  77908. var sourceKeys = source.animations[0].getKeys();
  77909. // rescaling prep
  77910. var sourceBoneLength = source.length;
  77911. var sourceParent = source.getParent();
  77912. var parent = this.getParent();
  77913. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77914. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77915. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77916. var destKeys = this.animations[0].getKeys();
  77917. // loop vars declaration
  77918. var orig;
  77919. var origTranslation;
  77920. var mat;
  77921. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77922. orig = sourceKeys[key];
  77923. if (orig.frame >= from && orig.frame <= to) {
  77924. if (rescaleAsRequired) {
  77925. mat = orig.value.clone();
  77926. // scale based on parent ratio, when bone has parent
  77927. if (parentScalingReqd) {
  77928. origTranslation = mat.getTranslation();
  77929. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77930. // scale based on skeleton dimension ratio when root bone, and value is passed
  77931. }
  77932. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77933. origTranslation = mat.getTranslation();
  77934. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77935. // use original when root bone, and no data for skelDimensionsRatio
  77936. }
  77937. else {
  77938. mat = orig.value;
  77939. }
  77940. }
  77941. else {
  77942. mat = orig.value;
  77943. }
  77944. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77945. }
  77946. }
  77947. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77948. return true;
  77949. };
  77950. /**
  77951. * Translate the bone in local or world space
  77952. * @param vec The amount to translate the bone
  77953. * @param space The space that the translation is in
  77954. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77955. */
  77956. Bone.prototype.translate = function (vec, space, mesh) {
  77957. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77958. var lm = this.getLocalMatrix();
  77959. if (space == BABYLON.Space.LOCAL) {
  77960. lm.m[12] += vec.x;
  77961. lm.m[13] += vec.y;
  77962. lm.m[14] += vec.z;
  77963. }
  77964. else {
  77965. var wm = null;
  77966. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77967. if (mesh) {
  77968. wm = mesh.getWorldMatrix();
  77969. }
  77970. this._skeleton.computeAbsoluteTransforms();
  77971. var tmat = Bone._tmpMats[0];
  77972. var tvec = Bone._tmpVecs[0];
  77973. if (this._parent) {
  77974. if (mesh && wm) {
  77975. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77976. tmat.multiplyToRef(wm, tmat);
  77977. }
  77978. else {
  77979. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77980. }
  77981. }
  77982. tmat.m[12] = 0;
  77983. tmat.m[13] = 0;
  77984. tmat.m[14] = 0;
  77985. tmat.invert();
  77986. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77987. lm.m[12] += tvec.x;
  77988. lm.m[13] += tvec.y;
  77989. lm.m[14] += tvec.z;
  77990. }
  77991. this._markAsDirtyAndDecompose();
  77992. };
  77993. /**
  77994. * Set the postion of the bone in local or world space
  77995. * @param position The position to set the bone
  77996. * @param space The space that the position is in
  77997. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77998. */
  77999. Bone.prototype.setPosition = function (position, space, mesh) {
  78000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78001. var lm = this.getLocalMatrix();
  78002. if (space == BABYLON.Space.LOCAL) {
  78003. lm.m[12] = position.x;
  78004. lm.m[13] = position.y;
  78005. lm.m[14] = position.z;
  78006. }
  78007. else {
  78008. var wm = null;
  78009. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78010. if (mesh) {
  78011. wm = mesh.getWorldMatrix();
  78012. }
  78013. this._skeleton.computeAbsoluteTransforms();
  78014. var tmat = Bone._tmpMats[0];
  78015. var vec = Bone._tmpVecs[0];
  78016. if (this._parent) {
  78017. if (mesh && wm) {
  78018. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78019. tmat.multiplyToRef(wm, tmat);
  78020. }
  78021. else {
  78022. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78023. }
  78024. }
  78025. tmat.invert();
  78026. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78027. lm.m[12] = vec.x;
  78028. lm.m[13] = vec.y;
  78029. lm.m[14] = vec.z;
  78030. }
  78031. this._markAsDirtyAndDecompose();
  78032. };
  78033. /**
  78034. * Set the absolute position of the bone (world space)
  78035. * @param position The position to set the bone
  78036. * @param mesh The mesh that this bone is attached to
  78037. */
  78038. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78039. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78040. };
  78041. /**
  78042. * Scale the bone on the x, y and z axes (in local space)
  78043. * @param x The amount to scale the bone on the x axis
  78044. * @param y The amount to scale the bone on the y axis
  78045. * @param z The amount to scale the bone on the z axis
  78046. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78047. */
  78048. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78049. if (scaleChildren === void 0) { scaleChildren = false; }
  78050. var locMat = this.getLocalMatrix();
  78051. // Apply new scaling on top of current local matrix
  78052. var scaleMat = Bone._tmpMats[0];
  78053. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78054. scaleMat.multiplyToRef(locMat, locMat);
  78055. // Invert scaling matrix and apply the inverse to all children
  78056. scaleMat.invert();
  78057. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78058. var child = _a[_i];
  78059. var cm = child.getLocalMatrix();
  78060. cm.multiplyToRef(scaleMat, cm);
  78061. cm.m[12] *= x;
  78062. cm.m[13] *= y;
  78063. cm.m[14] *= z;
  78064. child._markAsDirtyAndDecompose();
  78065. }
  78066. this._markAsDirtyAndDecompose();
  78067. if (scaleChildren) {
  78068. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78069. var child = _c[_b];
  78070. child.scale(x, y, z, scaleChildren);
  78071. }
  78072. }
  78073. };
  78074. /**
  78075. * Set the bone scaling in local space
  78076. * @param scale defines the scaling vector
  78077. */
  78078. Bone.prototype.setScale = function (scale) {
  78079. this._decompose();
  78080. this._localScaling.copyFrom(scale);
  78081. this._markAsDirtyAndCompose();
  78082. };
  78083. /**
  78084. * Gets the current scaling in local space
  78085. * @returns the current scaling vector
  78086. */
  78087. Bone.prototype.getScale = function () {
  78088. this._decompose();
  78089. return this._localScaling;
  78090. };
  78091. /**
  78092. * Gets the current scaling in local space and stores it in a target vector
  78093. * @param result defines the target vector
  78094. */
  78095. Bone.prototype.getScaleToRef = function (result) {
  78096. this._decompose();
  78097. result.copyFrom(this._localScaling);
  78098. };
  78099. /**
  78100. * Set the yaw, pitch, and roll of the bone in local or world space
  78101. * @param yaw The rotation of the bone on the y axis
  78102. * @param pitch The rotation of the bone on the x axis
  78103. * @param roll The rotation of the bone on the z axis
  78104. * @param space The space that the axes of rotation are in
  78105. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78106. */
  78107. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78109. if (space === BABYLON.Space.LOCAL) {
  78110. var quat = Bone._tmpQuat;
  78111. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78112. this.setRotationQuaternion(quat, space, mesh);
  78113. return;
  78114. }
  78115. var rotMatInv = Bone._tmpMats[0];
  78116. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78117. return;
  78118. }
  78119. var rotMat = Bone._tmpMats[1];
  78120. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78121. rotMatInv.multiplyToRef(rotMat, rotMat);
  78122. this._rotateWithMatrix(rotMat, space, mesh);
  78123. };
  78124. /**
  78125. * Add a rotation to the bone on an axis in local or world space
  78126. * @param axis The axis to rotate the bone on
  78127. * @param amount The amount to rotate the bone
  78128. * @param space The space that the axis is in
  78129. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78130. */
  78131. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78132. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78133. var rmat = Bone._tmpMats[0];
  78134. rmat.m[12] = 0;
  78135. rmat.m[13] = 0;
  78136. rmat.m[14] = 0;
  78137. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78138. this._rotateWithMatrix(rmat, space, mesh);
  78139. };
  78140. /**
  78141. * Set the rotation of the bone to a particular axis angle in local or world space
  78142. * @param axis The axis to rotate the bone on
  78143. * @param angle The angle that the bone should be rotated to
  78144. * @param space The space that the axis is in
  78145. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78146. */
  78147. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78148. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78149. if (space === BABYLON.Space.LOCAL) {
  78150. var quat = Bone._tmpQuat;
  78151. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78152. this.setRotationQuaternion(quat, space, mesh);
  78153. return;
  78154. }
  78155. var rotMatInv = Bone._tmpMats[0];
  78156. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78157. return;
  78158. }
  78159. var rotMat = Bone._tmpMats[1];
  78160. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78161. rotMatInv.multiplyToRef(rotMat, rotMat);
  78162. this._rotateWithMatrix(rotMat, space, mesh);
  78163. };
  78164. /**
  78165. * Set the euler rotation of the bone in local of world space
  78166. * @param rotation The euler rotation that the bone should be set to
  78167. * @param space The space that the rotation is in
  78168. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78169. */
  78170. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78172. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78173. };
  78174. /**
  78175. * Set the quaternion rotation of the bone in local of world space
  78176. * @param quat The quaternion rotation that the bone should be set to
  78177. * @param space The space that the rotation is in
  78178. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78179. */
  78180. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78181. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78182. if (space === BABYLON.Space.LOCAL) {
  78183. this._decompose();
  78184. this._localRotation.copyFrom(quat);
  78185. this._markAsDirtyAndCompose();
  78186. return;
  78187. }
  78188. var rotMatInv = Bone._tmpMats[0];
  78189. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78190. return;
  78191. }
  78192. var rotMat = Bone._tmpMats[1];
  78193. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78194. rotMatInv.multiplyToRef(rotMat, rotMat);
  78195. this._rotateWithMatrix(rotMat, space, mesh);
  78196. };
  78197. /**
  78198. * Set the rotation matrix of the bone in local of world space
  78199. * @param rotMat The rotation matrix that the bone should be set to
  78200. * @param space The space that the rotation is in
  78201. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78202. */
  78203. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78204. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78205. if (space === BABYLON.Space.LOCAL) {
  78206. var quat = Bone._tmpQuat;
  78207. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78208. this.setRotationQuaternion(quat, space, mesh);
  78209. return;
  78210. }
  78211. var rotMatInv = Bone._tmpMats[0];
  78212. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78213. return;
  78214. }
  78215. var rotMat2 = Bone._tmpMats[1];
  78216. rotMat2.copyFrom(rotMat);
  78217. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78218. this._rotateWithMatrix(rotMat2, space, mesh);
  78219. };
  78220. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78222. var lmat = this.getLocalMatrix();
  78223. var lx = lmat.m[12];
  78224. var ly = lmat.m[13];
  78225. var lz = lmat.m[14];
  78226. var parent = this.getParent();
  78227. var parentScale = Bone._tmpMats[3];
  78228. var parentScaleInv = Bone._tmpMats[4];
  78229. if (parent && space == BABYLON.Space.WORLD) {
  78230. if (mesh) {
  78231. parentScale.copyFrom(mesh.getWorldMatrix());
  78232. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78233. }
  78234. else {
  78235. parentScale.copyFrom(parent.getAbsoluteTransform());
  78236. }
  78237. parentScaleInv.copyFrom(parentScale);
  78238. parentScaleInv.invert();
  78239. lmat.multiplyToRef(parentScale, lmat);
  78240. lmat.multiplyToRef(rmat, lmat);
  78241. lmat.multiplyToRef(parentScaleInv, lmat);
  78242. }
  78243. else {
  78244. if (space == BABYLON.Space.WORLD && mesh) {
  78245. parentScale.copyFrom(mesh.getWorldMatrix());
  78246. parentScaleInv.copyFrom(parentScale);
  78247. parentScaleInv.invert();
  78248. lmat.multiplyToRef(parentScale, lmat);
  78249. lmat.multiplyToRef(rmat, lmat);
  78250. lmat.multiplyToRef(parentScaleInv, lmat);
  78251. }
  78252. else {
  78253. lmat.multiplyToRef(rmat, lmat);
  78254. }
  78255. }
  78256. lmat.m[12] = lx;
  78257. lmat.m[13] = ly;
  78258. lmat.m[14] = lz;
  78259. this.computeAbsoluteTransforms();
  78260. this._markAsDirtyAndDecompose();
  78261. };
  78262. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78263. var scaleMatrix = Bone._tmpMats[2];
  78264. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78265. if (mesh) {
  78266. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78267. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78268. }
  78269. rotMatInv.invert();
  78270. if (isNaN(rotMatInv.m[0])) {
  78271. // Matrix failed to invert.
  78272. // This can happen if scale is zero for example.
  78273. return false;
  78274. }
  78275. scaleMatrix.m[0] *= this._scalingDeterminant;
  78276. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78277. return true;
  78278. };
  78279. /**
  78280. * Get the position of the bone in local or world space
  78281. * @param space The space that the returned position is in
  78282. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78283. * @returns The position of the bone
  78284. */
  78285. Bone.prototype.getPosition = function (space, mesh) {
  78286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78287. if (mesh === void 0) { mesh = null; }
  78288. var pos = BABYLON.Vector3.Zero();
  78289. this.getPositionToRef(space, mesh, pos);
  78290. return pos;
  78291. };
  78292. /**
  78293. * Copy the position of the bone to a vector3 in local or world space
  78294. * @param space The space that the returned position is in
  78295. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78296. * @param result The vector3 to copy the position to
  78297. */
  78298. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78299. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78300. if (space == BABYLON.Space.LOCAL) {
  78301. var lm = this.getLocalMatrix();
  78302. result.x = lm.m[12];
  78303. result.y = lm.m[13];
  78304. result.z = lm.m[14];
  78305. }
  78306. else {
  78307. var wm = null;
  78308. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78309. if (mesh) {
  78310. wm = mesh.getWorldMatrix();
  78311. }
  78312. this._skeleton.computeAbsoluteTransforms();
  78313. var tmat = Bone._tmpMats[0];
  78314. if (mesh && wm) {
  78315. tmat.copyFrom(this.getAbsoluteTransform());
  78316. tmat.multiplyToRef(wm, tmat);
  78317. }
  78318. else {
  78319. tmat = this.getAbsoluteTransform();
  78320. }
  78321. result.x = tmat.m[12];
  78322. result.y = tmat.m[13];
  78323. result.z = tmat.m[14];
  78324. }
  78325. };
  78326. /**
  78327. * Get the absolute position of the bone (world space)
  78328. * @param mesh The mesh that this bone is attached to
  78329. * @returns The absolute position of the bone
  78330. */
  78331. Bone.prototype.getAbsolutePosition = function (mesh) {
  78332. if (mesh === void 0) { mesh = null; }
  78333. var pos = BABYLON.Vector3.Zero();
  78334. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78335. return pos;
  78336. };
  78337. /**
  78338. * Copy the absolute position of the bone (world space) to the result param
  78339. * @param mesh The mesh that this bone is attached to
  78340. * @param result The vector3 to copy the absolute position to
  78341. */
  78342. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78343. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78344. };
  78345. /**
  78346. * Compute the absolute transforms of this bone and its children
  78347. */
  78348. Bone.prototype.computeAbsoluteTransforms = function () {
  78349. this._compose();
  78350. if (this._parent) {
  78351. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78352. }
  78353. else {
  78354. this._absoluteTransform.copyFrom(this._localMatrix);
  78355. var poseMatrix = this._skeleton.getPoseMatrix();
  78356. if (poseMatrix) {
  78357. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78358. }
  78359. }
  78360. var children = this.children;
  78361. var len = children.length;
  78362. for (var i = 0; i < len; i++) {
  78363. children[i].computeAbsoluteTransforms();
  78364. }
  78365. };
  78366. /**
  78367. * Get the world direction from an axis that is in the local space of the bone
  78368. * @param localAxis The local direction that is used to compute the world direction
  78369. * @param mesh The mesh that this bone is attached to
  78370. * @returns The world direction
  78371. */
  78372. Bone.prototype.getDirection = function (localAxis, mesh) {
  78373. if (mesh === void 0) { mesh = null; }
  78374. var result = BABYLON.Vector3.Zero();
  78375. this.getDirectionToRef(localAxis, mesh, result);
  78376. return result;
  78377. };
  78378. /**
  78379. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78380. * @param localAxis The local direction that is used to compute the world direction
  78381. * @param mesh The mesh that this bone is attached to
  78382. * @param result The vector3 that the world direction will be copied to
  78383. */
  78384. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78385. if (mesh === void 0) { mesh = null; }
  78386. var wm = null;
  78387. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78388. if (mesh) {
  78389. wm = mesh.getWorldMatrix();
  78390. }
  78391. this._skeleton.computeAbsoluteTransforms();
  78392. var mat = Bone._tmpMats[0];
  78393. mat.copyFrom(this.getAbsoluteTransform());
  78394. if (mesh && wm) {
  78395. mat.multiplyToRef(wm, mat);
  78396. }
  78397. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78398. result.normalize();
  78399. };
  78400. /**
  78401. * Get the euler rotation of the bone in local or world space
  78402. * @param space The space that the rotation should be in
  78403. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78404. * @returns The euler rotation
  78405. */
  78406. Bone.prototype.getRotation = function (space, mesh) {
  78407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78408. if (mesh === void 0) { mesh = null; }
  78409. var result = BABYLON.Vector3.Zero();
  78410. this.getRotationToRef(space, mesh, result);
  78411. return result;
  78412. };
  78413. /**
  78414. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78415. * @param space The space that the rotation should be in
  78416. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78417. * @param result The vector3 that the rotation should be copied to
  78418. */
  78419. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78420. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78421. if (mesh === void 0) { mesh = null; }
  78422. var quat = Bone._tmpQuat;
  78423. this.getRotationQuaternionToRef(space, mesh, quat);
  78424. quat.toEulerAnglesToRef(result);
  78425. };
  78426. /**
  78427. * Get the quaternion rotation of the bone in either local or world space
  78428. * @param space The space that the rotation should be in
  78429. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78430. * @returns The quaternion rotation
  78431. */
  78432. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78434. if (mesh === void 0) { mesh = null; }
  78435. var result = BABYLON.Quaternion.Identity();
  78436. this.getRotationQuaternionToRef(space, mesh, result);
  78437. return result;
  78438. };
  78439. /**
  78440. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78441. * @param space The space that the rotation should be in
  78442. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78443. * @param result The quaternion that the rotation should be copied to
  78444. */
  78445. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78447. if (mesh === void 0) { mesh = null; }
  78448. if (space == BABYLON.Space.LOCAL) {
  78449. this._decompose();
  78450. result.copyFrom(this._localRotation);
  78451. }
  78452. else {
  78453. var mat = Bone._tmpMats[0];
  78454. var amat = this.getAbsoluteTransform();
  78455. if (mesh) {
  78456. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78457. }
  78458. else {
  78459. mat.copyFrom(amat);
  78460. }
  78461. mat.m[0] *= this._scalingDeterminant;
  78462. mat.m[1] *= this._scalingDeterminant;
  78463. mat.m[2] *= this._scalingDeterminant;
  78464. mat.decompose(undefined, result, undefined);
  78465. }
  78466. };
  78467. /**
  78468. * Get the rotation matrix of the bone in local or world space
  78469. * @param space The space that the rotation should be in
  78470. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78471. * @returns The rotation matrix
  78472. */
  78473. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78474. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78475. var result = BABYLON.Matrix.Identity();
  78476. this.getRotationMatrixToRef(space, mesh, result);
  78477. return result;
  78478. };
  78479. /**
  78480. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78481. * @param space The space that the rotation should be in
  78482. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78483. * @param result The quaternion that the rotation should be copied to
  78484. */
  78485. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78487. if (space == BABYLON.Space.LOCAL) {
  78488. this.getLocalMatrix().getRotationMatrixToRef(result);
  78489. }
  78490. else {
  78491. var mat = Bone._tmpMats[0];
  78492. var amat = this.getAbsoluteTransform();
  78493. if (mesh) {
  78494. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78495. }
  78496. else {
  78497. mat.copyFrom(amat);
  78498. }
  78499. mat.m[0] *= this._scalingDeterminant;
  78500. mat.m[1] *= this._scalingDeterminant;
  78501. mat.m[2] *= this._scalingDeterminant;
  78502. mat.getRotationMatrixToRef(result);
  78503. }
  78504. };
  78505. /**
  78506. * Get the world position of a point that is in the local space of the bone
  78507. * @param position The local position
  78508. * @param mesh The mesh that this bone is attached to
  78509. * @returns The world position
  78510. */
  78511. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78512. if (mesh === void 0) { mesh = null; }
  78513. var result = BABYLON.Vector3.Zero();
  78514. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78515. return result;
  78516. };
  78517. /**
  78518. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78519. * @param position The local position
  78520. * @param mesh The mesh that this bone is attached to
  78521. * @param result The vector3 that the world position should be copied to
  78522. */
  78523. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78524. if (mesh === void 0) { mesh = null; }
  78525. var wm = null;
  78526. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78527. if (mesh) {
  78528. wm = mesh.getWorldMatrix();
  78529. }
  78530. this._skeleton.computeAbsoluteTransforms();
  78531. var tmat = Bone._tmpMats[0];
  78532. if (mesh && wm) {
  78533. tmat.copyFrom(this.getAbsoluteTransform());
  78534. tmat.multiplyToRef(wm, tmat);
  78535. }
  78536. else {
  78537. tmat = this.getAbsoluteTransform();
  78538. }
  78539. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78540. };
  78541. /**
  78542. * Get the local position of a point that is in world space
  78543. * @param position The world position
  78544. * @param mesh The mesh that this bone is attached to
  78545. * @returns The local position
  78546. */
  78547. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78548. if (mesh === void 0) { mesh = null; }
  78549. var result = BABYLON.Vector3.Zero();
  78550. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78551. return result;
  78552. };
  78553. /**
  78554. * Get the local position of a point that is in world space and copy it to the result param
  78555. * @param position The world position
  78556. * @param mesh The mesh that this bone is attached to
  78557. * @param result The vector3 that the local position should be copied to
  78558. */
  78559. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78560. if (mesh === void 0) { mesh = null; }
  78561. var wm = null;
  78562. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78563. if (mesh) {
  78564. wm = mesh.getWorldMatrix();
  78565. }
  78566. this._skeleton.computeAbsoluteTransforms();
  78567. var tmat = Bone._tmpMats[0];
  78568. tmat.copyFrom(this.getAbsoluteTransform());
  78569. if (mesh && wm) {
  78570. tmat.multiplyToRef(wm, tmat);
  78571. }
  78572. tmat.invert();
  78573. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78574. };
  78575. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78576. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78577. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78578. return Bone;
  78579. }(BABYLON.Node));
  78580. BABYLON.Bone = Bone;
  78581. })(BABYLON || (BABYLON = {}));
  78582. //# sourceMappingURL=babylon.bone.js.map
  78583. var BABYLON;
  78584. (function (BABYLON) {
  78585. /**
  78586. * Class used to apply inverse kinematics to bones
  78587. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78588. */
  78589. var BoneIKController = /** @class */ (function () {
  78590. /**
  78591. * Creates a new BoneIKController
  78592. * @param mesh defines the mesh to control
  78593. * @param bone defines the bone to control
  78594. * @param options defines options to set up the controller
  78595. */
  78596. function BoneIKController(mesh, bone, options) {
  78597. /**
  78598. * Gets or sets the target position
  78599. */
  78600. this.targetPosition = BABYLON.Vector3.Zero();
  78601. /**
  78602. * Gets or sets the pole target position
  78603. */
  78604. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78605. /**
  78606. * Gets or sets the pole target local offset
  78607. */
  78608. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78609. /**
  78610. * Gets or sets the pole angle
  78611. */
  78612. this.poleAngle = 0;
  78613. /**
  78614. * 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)
  78615. */
  78616. this.slerpAmount = 1;
  78617. this._bone1Quat = BABYLON.Quaternion.Identity();
  78618. this._bone1Mat = BABYLON.Matrix.Identity();
  78619. this._bone2Ang = Math.PI;
  78620. this._maxAngle = Math.PI;
  78621. this._rightHandedSystem = false;
  78622. this._bendAxis = BABYLON.Vector3.Right();
  78623. this._slerping = false;
  78624. this._adjustRoll = 0;
  78625. this._bone2 = bone;
  78626. this._bone1 = bone.getParent();
  78627. if (!this._bone1) {
  78628. return;
  78629. }
  78630. this.mesh = mesh;
  78631. var bonePos = bone.getPosition();
  78632. if (bone.getAbsoluteTransform().determinant() > 0) {
  78633. this._rightHandedSystem = true;
  78634. this._bendAxis.x = 0;
  78635. this._bendAxis.y = 0;
  78636. this._bendAxis.z = -1;
  78637. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78638. this._adjustRoll = Math.PI * .5;
  78639. this._bendAxis.z = 1;
  78640. }
  78641. }
  78642. if (this._bone1.length) {
  78643. var boneScale1 = this._bone1.getScale();
  78644. var boneScale2 = this._bone2.getScale();
  78645. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78646. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78647. }
  78648. else if (this._bone1.children[0]) {
  78649. mesh.computeWorldMatrix(true);
  78650. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78651. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78652. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78653. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78654. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78655. }
  78656. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78657. this.maxAngle = Math.PI;
  78658. if (options) {
  78659. if (options.targetMesh) {
  78660. this.targetMesh = options.targetMesh;
  78661. this.targetMesh.computeWorldMatrix(true);
  78662. }
  78663. if (options.poleTargetMesh) {
  78664. this.poleTargetMesh = options.poleTargetMesh;
  78665. this.poleTargetMesh.computeWorldMatrix(true);
  78666. }
  78667. else if (options.poleTargetBone) {
  78668. this.poleTargetBone = options.poleTargetBone;
  78669. }
  78670. else if (this._bone1.getParent()) {
  78671. this.poleTargetBone = this._bone1.getParent();
  78672. }
  78673. if (options.poleTargetLocalOffset) {
  78674. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78675. }
  78676. if (options.poleAngle) {
  78677. this.poleAngle = options.poleAngle;
  78678. }
  78679. if (options.bendAxis) {
  78680. this._bendAxis.copyFrom(options.bendAxis);
  78681. }
  78682. if (options.maxAngle) {
  78683. this.maxAngle = options.maxAngle;
  78684. }
  78685. if (options.slerpAmount) {
  78686. this.slerpAmount = options.slerpAmount;
  78687. }
  78688. }
  78689. }
  78690. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78691. /**
  78692. * Gets or sets maximum allowed angle
  78693. */
  78694. get: function () {
  78695. return this._maxAngle;
  78696. },
  78697. set: function (value) {
  78698. this._setMaxAngle(value);
  78699. },
  78700. enumerable: true,
  78701. configurable: true
  78702. });
  78703. BoneIKController.prototype._setMaxAngle = function (ang) {
  78704. if (ang < 0) {
  78705. ang = 0;
  78706. }
  78707. if (ang > Math.PI || ang == undefined) {
  78708. ang = Math.PI;
  78709. }
  78710. this._maxAngle = ang;
  78711. var a = this._bone1Length;
  78712. var b = this._bone2Length;
  78713. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78714. };
  78715. /**
  78716. * Force the controller to update the bones
  78717. */
  78718. BoneIKController.prototype.update = function () {
  78719. var bone1 = this._bone1;
  78720. if (!bone1) {
  78721. return;
  78722. }
  78723. var target = this.targetPosition;
  78724. var poleTarget = this.poleTargetPosition;
  78725. var mat1 = BoneIKController._tmpMats[0];
  78726. var mat2 = BoneIKController._tmpMats[1];
  78727. if (this.targetMesh) {
  78728. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78729. }
  78730. if (this.poleTargetBone) {
  78731. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78732. }
  78733. else if (this.poleTargetMesh) {
  78734. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78735. }
  78736. var bonePos = BoneIKController._tmpVecs[0];
  78737. var zaxis = BoneIKController._tmpVecs[1];
  78738. var xaxis = BoneIKController._tmpVecs[2];
  78739. var yaxis = BoneIKController._tmpVecs[3];
  78740. var upAxis = BoneIKController._tmpVecs[4];
  78741. var _tmpQuat = BoneIKController._tmpQuat;
  78742. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78743. poleTarget.subtractToRef(bonePos, upAxis);
  78744. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78745. upAxis.y = 1;
  78746. }
  78747. else {
  78748. upAxis.normalize();
  78749. }
  78750. target.subtractToRef(bonePos, yaxis);
  78751. yaxis.normalize();
  78752. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78753. zaxis.normalize();
  78754. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78755. xaxis.normalize();
  78756. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78757. var a = this._bone1Length;
  78758. var b = this._bone2Length;
  78759. var c = BABYLON.Vector3.Distance(bonePos, target);
  78760. if (this._maxReach > 0) {
  78761. c = Math.min(this._maxReach, c);
  78762. }
  78763. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78764. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78765. if (acosa > 1) {
  78766. acosa = 1;
  78767. }
  78768. if (acosb > 1) {
  78769. acosb = 1;
  78770. }
  78771. if (acosa < -1) {
  78772. acosa = -1;
  78773. }
  78774. if (acosb < -1) {
  78775. acosb = -1;
  78776. }
  78777. var angA = Math.acos(acosa);
  78778. var angB = Math.acos(acosb);
  78779. var angC = -angA - angB;
  78780. if (this._rightHandedSystem) {
  78781. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78782. mat2.multiplyToRef(mat1, mat1);
  78783. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78784. mat2.multiplyToRef(mat1, mat1);
  78785. }
  78786. else {
  78787. var _tmpVec = BoneIKController._tmpVecs[5];
  78788. _tmpVec.copyFrom(this._bendAxis);
  78789. _tmpVec.x *= -1;
  78790. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78791. mat2.multiplyToRef(mat1, mat1);
  78792. }
  78793. if (this.poleAngle) {
  78794. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78795. mat1.multiplyToRef(mat2, mat1);
  78796. }
  78797. if (this._bone1) {
  78798. if (this.slerpAmount < 1) {
  78799. if (!this._slerping) {
  78800. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78801. }
  78802. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78803. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78804. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78805. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78806. this._slerping = true;
  78807. }
  78808. else {
  78809. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78810. this._bone1Mat.copyFrom(mat1);
  78811. this._slerping = false;
  78812. }
  78813. }
  78814. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78815. this._bone2Ang = angC;
  78816. };
  78817. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78818. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78819. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78820. return BoneIKController;
  78821. }());
  78822. BABYLON.BoneIKController = BoneIKController;
  78823. })(BABYLON || (BABYLON = {}));
  78824. //# sourceMappingURL=babylon.boneIKController.js.map
  78825. var BABYLON;
  78826. (function (BABYLON) {
  78827. /**
  78828. * Class used to make a bone look toward a point in space
  78829. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78830. */
  78831. var BoneLookController = /** @class */ (function () {
  78832. /**
  78833. * Create a BoneLookController
  78834. * @param mesh the mesh that the bone belongs to
  78835. * @param bone the bone that will be looking to the target
  78836. * @param target the target Vector3 to look at
  78837. * @param settings optional settings:
  78838. * * maxYaw: the maximum angle the bone will yaw to
  78839. * * minYaw: the minimum angle the bone will yaw to
  78840. * * maxPitch: the maximum angle the bone will pitch to
  78841. * * minPitch: the minimum angle the bone will yaw to
  78842. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78843. * * upAxis: the up axis of the coordinate system
  78844. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78845. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78846. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78847. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78848. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78849. * * adjustRoll: used to make an adjustment to the roll of the bone
  78850. **/
  78851. function BoneLookController(mesh, bone, target, options) {
  78852. /**
  78853. * The up axis of the coordinate system that is used when the bone is rotated
  78854. */
  78855. this.upAxis = BABYLON.Vector3.Up();
  78856. /**
  78857. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78858. */
  78859. this.upAxisSpace = BABYLON.Space.LOCAL;
  78860. /**
  78861. * Used to make an adjustment to the yaw of the bone
  78862. */
  78863. this.adjustYaw = 0;
  78864. /**
  78865. * Used to make an adjustment to the pitch of the bone
  78866. */
  78867. this.adjustPitch = 0;
  78868. /**
  78869. * Used to make an adjustment to the roll of the bone
  78870. */
  78871. this.adjustRoll = 0;
  78872. /**
  78873. * 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)
  78874. */
  78875. this.slerpAmount = 1;
  78876. this._boneQuat = BABYLON.Quaternion.Identity();
  78877. this._slerping = false;
  78878. this._firstFrameSkipped = false;
  78879. this._fowardAxis = BABYLON.Vector3.Forward();
  78880. this.mesh = mesh;
  78881. this.bone = bone;
  78882. this.target = target;
  78883. if (options) {
  78884. if (options.adjustYaw) {
  78885. this.adjustYaw = options.adjustYaw;
  78886. }
  78887. if (options.adjustPitch) {
  78888. this.adjustPitch = options.adjustPitch;
  78889. }
  78890. if (options.adjustRoll) {
  78891. this.adjustRoll = options.adjustRoll;
  78892. }
  78893. if (options.maxYaw != null) {
  78894. this.maxYaw = options.maxYaw;
  78895. }
  78896. else {
  78897. this.maxYaw = Math.PI;
  78898. }
  78899. if (options.minYaw != null) {
  78900. this.minYaw = options.minYaw;
  78901. }
  78902. else {
  78903. this.minYaw = -Math.PI;
  78904. }
  78905. if (options.maxPitch != null) {
  78906. this.maxPitch = options.maxPitch;
  78907. }
  78908. else {
  78909. this.maxPitch = Math.PI;
  78910. }
  78911. if (options.minPitch != null) {
  78912. this.minPitch = options.minPitch;
  78913. }
  78914. else {
  78915. this.minPitch = -Math.PI;
  78916. }
  78917. if (options.slerpAmount != null) {
  78918. this.slerpAmount = options.slerpAmount;
  78919. }
  78920. if (options.upAxis != null) {
  78921. this.upAxis = options.upAxis;
  78922. }
  78923. if (options.upAxisSpace != null) {
  78924. this.upAxisSpace = options.upAxisSpace;
  78925. }
  78926. if (options.yawAxis != null || options.pitchAxis != null) {
  78927. var newYawAxis = BABYLON.Axis.Y;
  78928. var newPitchAxis = BABYLON.Axis.X;
  78929. if (options.yawAxis != null) {
  78930. newYawAxis = options.yawAxis.clone();
  78931. newYawAxis.normalize();
  78932. }
  78933. if (options.pitchAxis != null) {
  78934. newPitchAxis = options.pitchAxis.clone();
  78935. newPitchAxis.normalize();
  78936. }
  78937. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78938. this._transformYawPitch = BABYLON.Matrix.Identity();
  78939. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78940. this._transformYawPitchInv = this._transformYawPitch.clone();
  78941. this._transformYawPitch.invert();
  78942. }
  78943. }
  78944. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78945. this.upAxisSpace = BABYLON.Space.LOCAL;
  78946. }
  78947. }
  78948. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78949. /**
  78950. * Gets or sets the minimum yaw angle that the bone can look to
  78951. */
  78952. get: function () {
  78953. return this._minYaw;
  78954. },
  78955. set: function (value) {
  78956. this._minYaw = value;
  78957. this._minYawSin = Math.sin(value);
  78958. this._minYawCos = Math.cos(value);
  78959. if (this._maxYaw != null) {
  78960. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78961. this._yawRange = this._maxYaw - this._minYaw;
  78962. }
  78963. },
  78964. enumerable: true,
  78965. configurable: true
  78966. });
  78967. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78968. /**
  78969. * Gets or sets the maximum yaw angle that the bone can look to
  78970. */
  78971. get: function () {
  78972. return this._maxYaw;
  78973. },
  78974. set: function (value) {
  78975. this._maxYaw = value;
  78976. this._maxYawSin = Math.sin(value);
  78977. this._maxYawCos = Math.cos(value);
  78978. if (this._minYaw != null) {
  78979. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78980. this._yawRange = this._maxYaw - this._minYaw;
  78981. }
  78982. },
  78983. enumerable: true,
  78984. configurable: true
  78985. });
  78986. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78987. /**
  78988. * Gets or sets the minimum pitch angle that the bone can look to
  78989. */
  78990. get: function () {
  78991. return this._minPitch;
  78992. },
  78993. set: function (value) {
  78994. this._minPitch = value;
  78995. this._minPitchTan = Math.tan(value);
  78996. },
  78997. enumerable: true,
  78998. configurable: true
  78999. });
  79000. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79001. /**
  79002. * Gets or sets the maximum pitch angle that the bone can look to
  79003. */
  79004. get: function () {
  79005. return this._maxPitch;
  79006. },
  79007. set: function (value) {
  79008. this._maxPitch = value;
  79009. this._maxPitchTan = Math.tan(value);
  79010. },
  79011. enumerable: true,
  79012. configurable: true
  79013. });
  79014. /**
  79015. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79016. */
  79017. BoneLookController.prototype.update = function () {
  79018. //skip the first frame when slerping so that the mesh rotation is correct
  79019. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79020. this._firstFrameSkipped = true;
  79021. return;
  79022. }
  79023. var bone = this.bone;
  79024. var bonePos = BoneLookController._tmpVecs[0];
  79025. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79026. var target = this.target;
  79027. var _tmpMat1 = BoneLookController._tmpMats[0];
  79028. var _tmpMat2 = BoneLookController._tmpMats[1];
  79029. var mesh = this.mesh;
  79030. var parentBone = bone.getParent();
  79031. var upAxis = BoneLookController._tmpVecs[1];
  79032. upAxis.copyFrom(this.upAxis);
  79033. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79034. if (this._transformYawPitch) {
  79035. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79036. }
  79037. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79038. }
  79039. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79040. mesh.getDirectionToRef(upAxis, upAxis);
  79041. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79042. upAxis.normalize();
  79043. }
  79044. }
  79045. var checkYaw = false;
  79046. var checkPitch = false;
  79047. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79048. checkYaw = true;
  79049. }
  79050. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79051. checkPitch = true;
  79052. }
  79053. if (checkYaw || checkPitch) {
  79054. var spaceMat = BoneLookController._tmpMats[2];
  79055. var spaceMatInv = BoneLookController._tmpMats[3];
  79056. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79057. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79058. }
  79059. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79060. spaceMat.copyFrom(mesh.getWorldMatrix());
  79061. }
  79062. else {
  79063. var forwardAxis = BoneLookController._tmpVecs[2];
  79064. forwardAxis.copyFrom(this._fowardAxis);
  79065. if (this._transformYawPitch) {
  79066. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79067. }
  79068. if (parentBone) {
  79069. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79070. }
  79071. else {
  79072. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79073. }
  79074. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79075. rightAxis.normalize();
  79076. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79077. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79078. }
  79079. spaceMat.invertToRef(spaceMatInv);
  79080. var xzlen = null;
  79081. if (checkPitch) {
  79082. var localTarget = BoneLookController._tmpVecs[3];
  79083. target.subtractToRef(bonePos, localTarget);
  79084. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79085. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79086. var pitch = Math.atan2(localTarget.y, xzlen);
  79087. var newPitch = pitch;
  79088. if (pitch > this._maxPitch) {
  79089. localTarget.y = this._maxPitchTan * xzlen;
  79090. newPitch = this._maxPitch;
  79091. }
  79092. else if (pitch < this._minPitch) {
  79093. localTarget.y = this._minPitchTan * xzlen;
  79094. newPitch = this._minPitch;
  79095. }
  79096. if (pitch != newPitch) {
  79097. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79098. localTarget.addInPlace(bonePos);
  79099. target = localTarget;
  79100. }
  79101. }
  79102. if (checkYaw) {
  79103. var localTarget = BoneLookController._tmpVecs[4];
  79104. target.subtractToRef(bonePos, localTarget);
  79105. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79106. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79107. var newYaw = yaw;
  79108. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79109. if (xzlen == null) {
  79110. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79111. }
  79112. if (this._yawRange > Math.PI) {
  79113. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79114. localTarget.z = this._maxYawCos * xzlen;
  79115. localTarget.x = this._maxYawSin * xzlen;
  79116. newYaw = this._maxYaw;
  79117. }
  79118. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79119. localTarget.z = this._minYawCos * xzlen;
  79120. localTarget.x = this._minYawSin * xzlen;
  79121. newYaw = this._minYaw;
  79122. }
  79123. }
  79124. else {
  79125. if (yaw > this._maxYaw) {
  79126. localTarget.z = this._maxYawCos * xzlen;
  79127. localTarget.x = this._maxYawSin * xzlen;
  79128. newYaw = this._maxYaw;
  79129. }
  79130. else if (yaw < this._minYaw) {
  79131. localTarget.z = this._minYawCos * xzlen;
  79132. localTarget.x = this._minYawSin * xzlen;
  79133. newYaw = this._minYaw;
  79134. }
  79135. }
  79136. }
  79137. if (this._slerping && this._yawRange > Math.PI) {
  79138. //are we going to be crossing into the min/max region?
  79139. var boneFwd = BoneLookController._tmpVecs[8];
  79140. boneFwd.copyFrom(BABYLON.Axis.Z);
  79141. if (this._transformYawPitch) {
  79142. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79143. }
  79144. var boneRotMat = BoneLookController._tmpMats[4];
  79145. this._boneQuat.toRotationMatrix(boneRotMat);
  79146. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79147. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79148. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79149. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79150. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79151. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79152. if (angBtwTar > angBtwMidYaw) {
  79153. if (xzlen == null) {
  79154. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79155. }
  79156. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79157. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79158. if (angBtwMin < angBtwMax) {
  79159. newYaw = boneYaw + Math.PI * .75;
  79160. localTarget.z = Math.cos(newYaw) * xzlen;
  79161. localTarget.x = Math.sin(newYaw) * xzlen;
  79162. }
  79163. else {
  79164. newYaw = boneYaw - Math.PI * .75;
  79165. localTarget.z = Math.cos(newYaw) * xzlen;
  79166. localTarget.x = Math.sin(newYaw) * xzlen;
  79167. }
  79168. }
  79169. }
  79170. if (yaw != newYaw) {
  79171. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79172. localTarget.addInPlace(bonePos);
  79173. target = localTarget;
  79174. }
  79175. }
  79176. }
  79177. var zaxis = BoneLookController._tmpVecs[5];
  79178. var xaxis = BoneLookController._tmpVecs[6];
  79179. var yaxis = BoneLookController._tmpVecs[7];
  79180. var _tmpQuat = BoneLookController._tmpQuat;
  79181. target.subtractToRef(bonePos, zaxis);
  79182. zaxis.normalize();
  79183. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79184. xaxis.normalize();
  79185. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79186. yaxis.normalize();
  79187. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79188. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79189. return;
  79190. }
  79191. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79192. return;
  79193. }
  79194. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79195. return;
  79196. }
  79197. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79198. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79199. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79200. }
  79201. if (this.slerpAmount < 1) {
  79202. if (!this._slerping) {
  79203. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79204. }
  79205. if (this._transformYawPitch) {
  79206. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79207. }
  79208. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79209. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79210. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79211. this._slerping = true;
  79212. }
  79213. else {
  79214. if (this._transformYawPitch) {
  79215. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79216. }
  79217. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79218. this._slerping = false;
  79219. }
  79220. };
  79221. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79222. var angDiff = ang2 - ang1;
  79223. angDiff %= Math.PI * 2;
  79224. if (angDiff > Math.PI) {
  79225. angDiff -= Math.PI * 2;
  79226. }
  79227. else if (angDiff < -Math.PI) {
  79228. angDiff += Math.PI * 2;
  79229. }
  79230. return angDiff;
  79231. };
  79232. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79233. ang1 %= (2 * Math.PI);
  79234. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79235. ang2 %= (2 * Math.PI);
  79236. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79237. var ab = 0;
  79238. if (ang1 < ang2) {
  79239. ab = ang2 - ang1;
  79240. }
  79241. else {
  79242. ab = ang1 - ang2;
  79243. }
  79244. if (ab > Math.PI) {
  79245. ab = Math.PI * 2 - ab;
  79246. }
  79247. return ab;
  79248. };
  79249. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79250. ang %= (2 * Math.PI);
  79251. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79252. ang1 %= (2 * Math.PI);
  79253. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79254. ang2 %= (2 * Math.PI);
  79255. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79256. if (ang1 < ang2) {
  79257. if (ang > ang1 && ang < ang2) {
  79258. return true;
  79259. }
  79260. }
  79261. else {
  79262. if (ang > ang2 && ang < ang1) {
  79263. return true;
  79264. }
  79265. }
  79266. return false;
  79267. };
  79268. 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()];
  79269. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79270. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79271. return BoneLookController;
  79272. }());
  79273. BABYLON.BoneLookController = BoneLookController;
  79274. })(BABYLON || (BABYLON = {}));
  79275. //# sourceMappingURL=babylon.boneLookController.js.map
  79276. var BABYLON;
  79277. (function (BABYLON) {
  79278. /**
  79279. * Class used to handle skinning animations
  79280. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79281. */
  79282. var Skeleton = /** @class */ (function () {
  79283. /**
  79284. * Creates a new skeleton
  79285. * @param name defines the skeleton name
  79286. * @param id defines the skeleton Id
  79287. * @param scene defines the hosting scene
  79288. */
  79289. function Skeleton(
  79290. /** defines the skeleton name */
  79291. name,
  79292. /** defines the skeleton Id */
  79293. id, scene) {
  79294. this.name = name;
  79295. this.id = id;
  79296. /**
  79297. * Gets the list of child bones
  79298. */
  79299. this.bones = new Array();
  79300. /**
  79301. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79302. */
  79303. this.needInitialSkinMatrix = false;
  79304. this._isDirty = true;
  79305. this._meshesWithPoseMatrix = new Array();
  79306. this._identity = BABYLON.Matrix.Identity();
  79307. this._ranges = {};
  79308. this._lastAbsoluteTransformsUpdateId = -1;
  79309. /**
  79310. * Specifies if the skeleton should be serialized
  79311. */
  79312. this.doNotSerialize = false;
  79313. this._animationPropertiesOverride = null;
  79314. // Events
  79315. /**
  79316. * An observable triggered before computing the skeleton's matrices
  79317. */
  79318. this.onBeforeComputeObservable = new BABYLON.Observable();
  79319. this.bones = [];
  79320. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79321. scene.skeletons.push(this);
  79322. //make sure it will recalculate the matrix next time prepare is called.
  79323. this._isDirty = true;
  79324. }
  79325. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79326. /**
  79327. * Gets or sets the animation properties override
  79328. */
  79329. get: function () {
  79330. if (!this._animationPropertiesOverride) {
  79331. return this._scene.animationPropertiesOverride;
  79332. }
  79333. return this._animationPropertiesOverride;
  79334. },
  79335. set: function (value) {
  79336. this._animationPropertiesOverride = value;
  79337. },
  79338. enumerable: true,
  79339. configurable: true
  79340. });
  79341. // Members
  79342. /**
  79343. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79344. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79345. * @returns a Float32Array containing matrices data
  79346. */
  79347. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79348. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79349. return mesh._bonesTransformMatrices;
  79350. }
  79351. if (!this._transformMatrices) {
  79352. this.prepare();
  79353. }
  79354. return this._transformMatrices;
  79355. };
  79356. /**
  79357. * Gets the current hosting scene
  79358. * @returns a scene object
  79359. */
  79360. Skeleton.prototype.getScene = function () {
  79361. return this._scene;
  79362. };
  79363. // Methods
  79364. /**
  79365. * Gets a string representing the current skeleton data
  79366. * @param fullDetails defines a boolean indicating if we want a verbose version
  79367. * @returns a string representing the current skeleton data
  79368. */
  79369. Skeleton.prototype.toString = function (fullDetails) {
  79370. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79371. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79372. if (fullDetails) {
  79373. ret += ", Ranges: {";
  79374. var first = true;
  79375. for (var name_1 in this._ranges) {
  79376. if (first) {
  79377. ret += ", ";
  79378. first = false;
  79379. }
  79380. ret += name_1;
  79381. }
  79382. ret += "}";
  79383. }
  79384. return ret;
  79385. };
  79386. /**
  79387. * Get bone's index searching by name
  79388. * @param name defines bone's name to search for
  79389. * @return the indice of the bone. Returns -1 if not found
  79390. */
  79391. Skeleton.prototype.getBoneIndexByName = function (name) {
  79392. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79393. if (this.bones[boneIndex].name === name) {
  79394. return boneIndex;
  79395. }
  79396. }
  79397. return -1;
  79398. };
  79399. /**
  79400. * Creater a new animation range
  79401. * @param name defines the name of the range
  79402. * @param from defines the start key
  79403. * @param to defines the end key
  79404. */
  79405. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79406. // check name not already in use
  79407. if (!this._ranges[name]) {
  79408. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79409. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79410. if (this.bones[i].animations[0]) {
  79411. this.bones[i].animations[0].createRange(name, from, to);
  79412. }
  79413. }
  79414. }
  79415. };
  79416. /**
  79417. * Delete a specific animation range
  79418. * @param name defines the name of the range
  79419. * @param deleteFrames defines if frames must be removed as well
  79420. */
  79421. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79422. if (deleteFrames === void 0) { deleteFrames = true; }
  79423. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79424. if (this.bones[i].animations[0]) {
  79425. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79426. }
  79427. }
  79428. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79429. };
  79430. /**
  79431. * Gets a specific animation range
  79432. * @param name defines the name of the range to look for
  79433. * @returns the requested animation range or null if not found
  79434. */
  79435. Skeleton.prototype.getAnimationRange = function (name) {
  79436. return this._ranges[name];
  79437. };
  79438. /**
  79439. * Gets the list of all animation ranges defined on this skeleton
  79440. * @returns an array
  79441. */
  79442. Skeleton.prototype.getAnimationRanges = function () {
  79443. var animationRanges = [];
  79444. var name;
  79445. var i = 0;
  79446. for (name in this._ranges) {
  79447. animationRanges[i] = this._ranges[name];
  79448. i++;
  79449. }
  79450. return animationRanges;
  79451. };
  79452. /**
  79453. * Copy animation range from a source skeleton.
  79454. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79455. * @param source defines the source skeleton
  79456. * @param name defines the name of the range to copy
  79457. * @param rescaleAsRequired defines if rescaling must be applied if required
  79458. * @returns true if operation was successful
  79459. */
  79460. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79461. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79462. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79463. return false;
  79464. }
  79465. var ret = true;
  79466. var frameOffset = this._getHighestAnimationFrame() + 1;
  79467. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79468. var boneDict = {};
  79469. var sourceBones = source.bones;
  79470. var nBones;
  79471. var i;
  79472. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79473. boneDict[sourceBones[i].name] = sourceBones[i];
  79474. }
  79475. if (this.bones.length !== sourceBones.length) {
  79476. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79477. ret = false;
  79478. }
  79479. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79480. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79481. var boneName = this.bones[i].name;
  79482. var sourceBone = boneDict[boneName];
  79483. if (sourceBone) {
  79484. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79485. }
  79486. else {
  79487. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79488. ret = false;
  79489. }
  79490. }
  79491. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79492. var range = source.getAnimationRange(name);
  79493. if (range) {
  79494. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79495. }
  79496. return ret;
  79497. };
  79498. /**
  79499. * Forces the skeleton to go to rest pose
  79500. */
  79501. Skeleton.prototype.returnToRest = function () {
  79502. for (var index = 0; index < this.bones.length; index++) {
  79503. this.bones[index].returnToRest();
  79504. }
  79505. };
  79506. Skeleton.prototype._getHighestAnimationFrame = function () {
  79507. var ret = 0;
  79508. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79509. if (this.bones[i].animations[0]) {
  79510. var highest = this.bones[i].animations[0].getHighestFrame();
  79511. if (ret < highest) {
  79512. ret = highest;
  79513. }
  79514. }
  79515. }
  79516. return ret;
  79517. };
  79518. /**
  79519. * Begin a specific animation range
  79520. * @param name defines the name of the range to start
  79521. * @param loop defines if looping must be turned on (false by default)
  79522. * @param speedRatio defines the speed ratio to apply (1 by default)
  79523. * @param onAnimationEnd defines a callback which will be called when animation will end
  79524. * @returns a new animatable
  79525. */
  79526. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79527. var range = this.getAnimationRange(name);
  79528. if (!range) {
  79529. return null;
  79530. }
  79531. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79532. };
  79533. /** @hidden */
  79534. Skeleton.prototype._markAsDirty = function () {
  79535. this._isDirty = true;
  79536. };
  79537. /** @hidden */
  79538. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79539. this._meshesWithPoseMatrix.push(mesh);
  79540. };
  79541. /** @hidden */
  79542. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79543. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79544. if (index > -1) {
  79545. this._meshesWithPoseMatrix.splice(index, 1);
  79546. }
  79547. };
  79548. /** @hidden */
  79549. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79550. this.onBeforeComputeObservable.notifyObservers(this);
  79551. for (var index = 0; index < this.bones.length; index++) {
  79552. var bone = this.bones[index];
  79553. var parentBone = bone.getParent();
  79554. if (parentBone) {
  79555. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79556. }
  79557. else {
  79558. if (initialSkinMatrix) {
  79559. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79560. }
  79561. else {
  79562. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79563. }
  79564. }
  79565. if (bone._index !== -1) {
  79566. var mappedIndex = bone._index === null ? index : bone._index;
  79567. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79568. }
  79569. }
  79570. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79571. };
  79572. /**
  79573. * Build all resources required to render a skeleton
  79574. */
  79575. Skeleton.prototype.prepare = function () {
  79576. if (!this._isDirty) {
  79577. return;
  79578. }
  79579. if (this.needInitialSkinMatrix) {
  79580. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79581. var mesh = this._meshesWithPoseMatrix[index];
  79582. var poseMatrix = mesh.getPoseMatrix();
  79583. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79584. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79585. }
  79586. if (this._synchronizedWithMesh !== mesh) {
  79587. this._synchronizedWithMesh = mesh;
  79588. // Prepare bones
  79589. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79590. var bone = this.bones[boneIndex];
  79591. if (!bone.getParent()) {
  79592. var matrix = bone.getBaseMatrix();
  79593. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79594. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79595. }
  79596. }
  79597. }
  79598. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79599. }
  79600. }
  79601. else {
  79602. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79603. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79604. }
  79605. this._computeTransformMatrices(this._transformMatrices, null);
  79606. }
  79607. this._isDirty = false;
  79608. this._scene._activeBones.addCount(this.bones.length, false);
  79609. };
  79610. /**
  79611. * Gets the list of animatables currently running for this skeleton
  79612. * @returns an array of animatables
  79613. */
  79614. Skeleton.prototype.getAnimatables = function () {
  79615. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79616. this._animatables = [];
  79617. for (var index = 0; index < this.bones.length; index++) {
  79618. this._animatables.push(this.bones[index]);
  79619. }
  79620. }
  79621. return this._animatables;
  79622. };
  79623. /**
  79624. * Clone the current skeleton
  79625. * @param name defines the name of the new skeleton
  79626. * @param id defines the id of the enw skeleton
  79627. * @returns the new skeleton
  79628. */
  79629. Skeleton.prototype.clone = function (name, id) {
  79630. var result = new Skeleton(name, id || name, this._scene);
  79631. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79632. for (var index = 0; index < this.bones.length; index++) {
  79633. var source = this.bones[index];
  79634. var parentBone = null;
  79635. var parent_1 = source.getParent();
  79636. if (parent_1) {
  79637. var parentIndex = this.bones.indexOf(parent_1);
  79638. parentBone = result.bones[parentIndex];
  79639. }
  79640. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79641. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79642. }
  79643. if (this._ranges) {
  79644. result._ranges = {};
  79645. for (var rangeName in this._ranges) {
  79646. var range = this._ranges[rangeName];
  79647. if (range) {
  79648. result._ranges[rangeName] = range.clone();
  79649. }
  79650. }
  79651. }
  79652. this._isDirty = true;
  79653. return result;
  79654. };
  79655. /**
  79656. * Enable animation blending for this skeleton
  79657. * @param blendingSpeed defines the blending speed to apply
  79658. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79659. */
  79660. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79661. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79662. this.bones.forEach(function (bone) {
  79663. bone.animations.forEach(function (animation) {
  79664. animation.enableBlending = true;
  79665. animation.blendingSpeed = blendingSpeed;
  79666. });
  79667. });
  79668. };
  79669. /**
  79670. * Releases all resources associated with the current skeleton
  79671. */
  79672. Skeleton.prototype.dispose = function () {
  79673. this._meshesWithPoseMatrix = [];
  79674. // Animations
  79675. this.getScene().stopAnimation(this);
  79676. // Remove from scene
  79677. this.getScene().removeSkeleton(this);
  79678. };
  79679. /**
  79680. * Serialize the skeleton in a JSON object
  79681. * @returns a JSON object
  79682. */
  79683. Skeleton.prototype.serialize = function () {
  79684. var serializationObject = {};
  79685. serializationObject.name = this.name;
  79686. serializationObject.id = this.id;
  79687. if (this.dimensionsAtRest) {
  79688. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79689. }
  79690. serializationObject.bones = [];
  79691. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79692. for (var index = 0; index < this.bones.length; index++) {
  79693. var bone = this.bones[index];
  79694. var parent_2 = bone.getParent();
  79695. var serializedBone = {
  79696. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79697. name: bone.name,
  79698. matrix: bone.getBaseMatrix().toArray(),
  79699. rest: bone.getRestPose().toArray()
  79700. };
  79701. serializationObject.bones.push(serializedBone);
  79702. if (bone.length) {
  79703. serializedBone.length = bone.length;
  79704. }
  79705. if (bone.metadata) {
  79706. serializedBone.metadata = bone.metadata;
  79707. }
  79708. if (bone.animations && bone.animations.length > 0) {
  79709. serializedBone.animation = bone.animations[0].serialize();
  79710. }
  79711. serializationObject.ranges = [];
  79712. for (var name in this._ranges) {
  79713. var source = this._ranges[name];
  79714. if (!source) {
  79715. continue;
  79716. }
  79717. var range = {};
  79718. range.name = name;
  79719. range.from = source.from;
  79720. range.to = source.to;
  79721. serializationObject.ranges.push(range);
  79722. }
  79723. }
  79724. return serializationObject;
  79725. };
  79726. /**
  79727. * Creates a new skeleton from serialized data
  79728. * @param parsedSkeleton defines the serialized data
  79729. * @param scene defines the hosting scene
  79730. * @returns a new skeleton
  79731. */
  79732. Skeleton.Parse = function (parsedSkeleton, scene) {
  79733. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79734. if (parsedSkeleton.dimensionsAtRest) {
  79735. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79736. }
  79737. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79738. var index;
  79739. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79740. var parsedBone = parsedSkeleton.bones[index];
  79741. var parentBone = null;
  79742. if (parsedBone.parentBoneIndex > -1) {
  79743. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79744. }
  79745. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79746. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79747. if (parsedBone.length) {
  79748. bone.length = parsedBone.length;
  79749. }
  79750. if (parsedBone.metadata) {
  79751. bone.metadata = parsedBone.metadata;
  79752. }
  79753. if (parsedBone.animation) {
  79754. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79755. }
  79756. }
  79757. // placed after bones, so createAnimationRange can cascade down
  79758. if (parsedSkeleton.ranges) {
  79759. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79760. var data = parsedSkeleton.ranges[index];
  79761. skeleton.createAnimationRange(data.name, data.from, data.to);
  79762. }
  79763. }
  79764. return skeleton;
  79765. };
  79766. /**
  79767. * Compute all node absolute transforms
  79768. * @param forceUpdate defines if computation must be done even if cache is up to date
  79769. */
  79770. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79771. if (forceUpdate === void 0) { forceUpdate = false; }
  79772. var renderId = this._scene.getRenderId();
  79773. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79774. this.bones[0].computeAbsoluteTransforms();
  79775. this._lastAbsoluteTransformsUpdateId = renderId;
  79776. }
  79777. };
  79778. /**
  79779. * Gets the root pose matrix
  79780. * @returns a matrix
  79781. */
  79782. Skeleton.prototype.getPoseMatrix = function () {
  79783. var poseMatrix = null;
  79784. if (this._meshesWithPoseMatrix.length > 0) {
  79785. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79786. }
  79787. return poseMatrix;
  79788. };
  79789. /**
  79790. * Sorts bones per internal index
  79791. */
  79792. Skeleton.prototype.sortBones = function () {
  79793. var bones = new Array();
  79794. var visited = new Array(this.bones.length);
  79795. for (var index = 0; index < this.bones.length; index++) {
  79796. this._sortBones(index, bones, visited);
  79797. }
  79798. this.bones = bones;
  79799. };
  79800. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79801. if (visited[index]) {
  79802. return;
  79803. }
  79804. visited[index] = true;
  79805. var bone = this.bones[index];
  79806. if (bone._index === undefined) {
  79807. bone._index = index;
  79808. }
  79809. var parentBone = bone.getParent();
  79810. if (parentBone) {
  79811. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79812. }
  79813. bones.push(bone);
  79814. };
  79815. return Skeleton;
  79816. }());
  79817. BABYLON.Skeleton = Skeleton;
  79818. })(BABYLON || (BABYLON = {}));
  79819. //# sourceMappingURL=babylon.skeleton.js.map
  79820. var BABYLON;
  79821. (function (BABYLON) {
  79822. var SphericalPolynomial = /** @class */ (function () {
  79823. function SphericalPolynomial() {
  79824. this.x = BABYLON.Vector3.Zero();
  79825. this.y = BABYLON.Vector3.Zero();
  79826. this.z = BABYLON.Vector3.Zero();
  79827. this.xx = BABYLON.Vector3.Zero();
  79828. this.yy = BABYLON.Vector3.Zero();
  79829. this.zz = BABYLON.Vector3.Zero();
  79830. this.xy = BABYLON.Vector3.Zero();
  79831. this.yz = BABYLON.Vector3.Zero();
  79832. this.zx = BABYLON.Vector3.Zero();
  79833. }
  79834. SphericalPolynomial.prototype.addAmbient = function (color) {
  79835. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79836. this.xx = this.xx.add(colorVector);
  79837. this.yy = this.yy.add(colorVector);
  79838. this.zz = this.zz.add(colorVector);
  79839. };
  79840. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79841. var result = new SphericalPolynomial();
  79842. result.x = harmonics.L11.scale(1.02333);
  79843. result.y = harmonics.L1_1.scale(1.02333);
  79844. result.z = harmonics.L10.scale(1.02333);
  79845. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79846. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79847. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79848. result.yz = harmonics.L2_1.scale(0.858086);
  79849. result.zx = harmonics.L21.scale(0.858086);
  79850. result.xy = harmonics.L2_2.scale(0.858086);
  79851. result.scale(1.0 / Math.PI);
  79852. return result;
  79853. };
  79854. SphericalPolynomial.prototype.scale = function (scale) {
  79855. this.x = this.x.scale(scale);
  79856. this.y = this.y.scale(scale);
  79857. this.z = this.z.scale(scale);
  79858. this.xx = this.xx.scale(scale);
  79859. this.yy = this.yy.scale(scale);
  79860. this.zz = this.zz.scale(scale);
  79861. this.yz = this.yz.scale(scale);
  79862. this.zx = this.zx.scale(scale);
  79863. this.xy = this.xy.scale(scale);
  79864. };
  79865. return SphericalPolynomial;
  79866. }());
  79867. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79868. var SphericalHarmonics = /** @class */ (function () {
  79869. function SphericalHarmonics() {
  79870. this.L00 = BABYLON.Vector3.Zero();
  79871. this.L1_1 = BABYLON.Vector3.Zero();
  79872. this.L10 = BABYLON.Vector3.Zero();
  79873. this.L11 = BABYLON.Vector3.Zero();
  79874. this.L2_2 = BABYLON.Vector3.Zero();
  79875. this.L2_1 = BABYLON.Vector3.Zero();
  79876. this.L20 = BABYLON.Vector3.Zero();
  79877. this.L21 = BABYLON.Vector3.Zero();
  79878. this.L22 = BABYLON.Vector3.Zero();
  79879. }
  79880. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79881. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79882. var c = colorVector.scale(deltaSolidAngle);
  79883. this.L00 = this.L00.add(c.scale(0.282095));
  79884. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79885. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79886. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79887. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79888. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79889. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79890. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79891. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79892. };
  79893. SphericalHarmonics.prototype.scale = function (scale) {
  79894. this.L00 = this.L00.scale(scale);
  79895. this.L1_1 = this.L1_1.scale(scale);
  79896. this.L10 = this.L10.scale(scale);
  79897. this.L11 = this.L11.scale(scale);
  79898. this.L2_2 = this.L2_2.scale(scale);
  79899. this.L2_1 = this.L2_1.scale(scale);
  79900. this.L20 = this.L20.scale(scale);
  79901. this.L21 = this.L21.scale(scale);
  79902. this.L22 = this.L22.scale(scale);
  79903. };
  79904. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79905. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79906. //
  79907. // E_lm = A_l * L_lm
  79908. //
  79909. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79910. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79911. // the scaling factors are given in equation 9.
  79912. // Constant (Band 0)
  79913. this.L00 = this.L00.scale(3.141593);
  79914. // Linear (Band 1)
  79915. this.L1_1 = this.L1_1.scale(2.094395);
  79916. this.L10 = this.L10.scale(2.094395);
  79917. this.L11 = this.L11.scale(2.094395);
  79918. // Quadratic (Band 2)
  79919. this.L2_2 = this.L2_2.scale(0.785398);
  79920. this.L2_1 = this.L2_1.scale(0.785398);
  79921. this.L20 = this.L20.scale(0.785398);
  79922. this.L21 = this.L21.scale(0.785398);
  79923. this.L22 = this.L22.scale(0.785398);
  79924. };
  79925. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79926. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79927. // L = (1/pi) * E * rho
  79928. //
  79929. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79930. this.scale(1.0 / Math.PI);
  79931. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79932. // (The pixel shader must apply albedo after texture fetches, etc).
  79933. };
  79934. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79935. var result = new SphericalHarmonics();
  79936. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79937. result.L1_1 = polynomial.y.scale(0.977204);
  79938. result.L10 = polynomial.z.scale(0.977204);
  79939. result.L11 = polynomial.x.scale(0.977204);
  79940. result.L2_2 = polynomial.xy.scale(1.16538);
  79941. result.L2_1 = polynomial.yz.scale(1.16538);
  79942. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79943. result.L21 = polynomial.zx.scale(1.16538);
  79944. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79945. result.scale(Math.PI);
  79946. return result;
  79947. };
  79948. return SphericalHarmonics;
  79949. }());
  79950. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79951. })(BABYLON || (BABYLON = {}));
  79952. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79953. var BABYLON;
  79954. (function (BABYLON) {
  79955. var FileFaceOrientation = /** @class */ (function () {
  79956. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79957. this.name = name;
  79958. this.worldAxisForNormal = worldAxisForNormal;
  79959. this.worldAxisForFileX = worldAxisForFileX;
  79960. this.worldAxisForFileY = worldAxisForFileY;
  79961. }
  79962. return FileFaceOrientation;
  79963. }());
  79964. ;
  79965. /**
  79966. * Helper class dealing with the extraction of spherical polynomial dataArray
  79967. * from a cube map.
  79968. */
  79969. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79970. function CubeMapToSphericalPolynomialTools() {
  79971. }
  79972. /**
  79973. * Converts a texture to the according Spherical Polynomial data.
  79974. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79975. *
  79976. * @param texture The texture to extract the information from.
  79977. * @return The Spherical Polynomial data.
  79978. */
  79979. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79980. if (!texture.isCube) {
  79981. // Only supports cube Textures currently.
  79982. return null;
  79983. }
  79984. var size = texture.getSize().width;
  79985. var right = texture.readPixels(0);
  79986. var left = texture.readPixels(1);
  79987. var up;
  79988. var down;
  79989. if (texture.isRenderTarget) {
  79990. up = texture.readPixels(3);
  79991. down = texture.readPixels(2);
  79992. }
  79993. else {
  79994. up = texture.readPixels(2);
  79995. down = texture.readPixels(3);
  79996. }
  79997. var front = texture.readPixels(4);
  79998. var back = texture.readPixels(5);
  79999. var gammaSpace = texture.gammaSpace;
  80000. // Always read as RGBA.
  80001. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80002. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80003. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80004. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80005. }
  80006. var cubeInfo = {
  80007. size: size,
  80008. right: right,
  80009. left: left,
  80010. up: up,
  80011. down: down,
  80012. front: front,
  80013. back: back,
  80014. format: format,
  80015. type: type,
  80016. gammaSpace: gammaSpace,
  80017. };
  80018. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80019. };
  80020. /**
  80021. * Converts a cubemap to the according Spherical Polynomial data.
  80022. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80023. *
  80024. * @param cubeInfo The Cube map to extract the information from.
  80025. * @return The Spherical Polynomial data.
  80026. */
  80027. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80028. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80029. var totalSolidAngle = 0.0;
  80030. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80031. var du = 2.0 / cubeInfo.size;
  80032. var dv = du;
  80033. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80034. var minUV = du * 0.5 - 1.0;
  80035. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80036. var fileFace = this.FileFaces[faceIndex];
  80037. var dataArray = cubeInfo[fileFace.name];
  80038. var v = minUV;
  80039. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80040. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80041. // Because SP is still linear, so summation is fine in that basis.
  80042. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80043. for (var y = 0; y < cubeInfo.size; y++) {
  80044. var u = minUV;
  80045. for (var x = 0; x < cubeInfo.size; x++) {
  80046. // World direction (not normalised)
  80047. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80048. worldDirection.normalize();
  80049. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80050. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80051. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80052. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80053. // Handle Integer types.
  80054. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80055. r /= 255;
  80056. g /= 255;
  80057. b /= 255;
  80058. }
  80059. // Handle Gamma space textures.
  80060. if (cubeInfo.gammaSpace) {
  80061. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80062. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80063. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80064. }
  80065. var color = new BABYLON.Color3(r, g, b);
  80066. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80067. totalSolidAngle += deltaSolidAngle;
  80068. u += du;
  80069. }
  80070. v += dv;
  80071. }
  80072. }
  80073. // Solid angle for entire sphere is 4*pi
  80074. var sphereSolidAngle = 4.0 * Math.PI;
  80075. // Adjust the solid angle to allow for how many faces we processed.
  80076. var facesProcessed = 6.0;
  80077. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80078. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80079. // This is needed because the numerical integration over the cube uses a
  80080. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80081. // and also to compensate for accumulative error due to float precision in the summation.
  80082. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80083. sphericalHarmonics.scale(correctionFactor);
  80084. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80085. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80086. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80087. };
  80088. CubeMapToSphericalPolynomialTools.FileFaces = [
  80089. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80090. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80091. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80092. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80093. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80094. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80095. ];
  80096. return CubeMapToSphericalPolynomialTools;
  80097. }());
  80098. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80099. })(BABYLON || (BABYLON = {}));
  80100. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80101. var BABYLON;
  80102. (function (BABYLON) {
  80103. /**
  80104. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80105. */
  80106. var PanoramaToCubeMapTools = /** @class */ (function () {
  80107. function PanoramaToCubeMapTools() {
  80108. }
  80109. /**
  80110. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80111. *
  80112. * @param float32Array The source data.
  80113. * @param inputWidth The width of the input panorama.
  80114. * @param inputhHeight The height of the input panorama.
  80115. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80116. * @return The cubemap data
  80117. */
  80118. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80119. if (!float32Array) {
  80120. throw "ConvertPanoramaToCubemap: input cannot be null";
  80121. }
  80122. if (float32Array.length != inputWidth * inputHeight * 3) {
  80123. throw "ConvertPanoramaToCubemap: input size is wrong";
  80124. }
  80125. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80126. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80127. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80128. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80129. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80130. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80131. return {
  80132. front: textureFront,
  80133. back: textureBack,
  80134. left: textureLeft,
  80135. right: textureRight,
  80136. up: textureUp,
  80137. down: textureDown,
  80138. size: size,
  80139. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80140. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80141. gammaSpace: false,
  80142. };
  80143. };
  80144. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80145. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80146. var textureArray = new Float32Array(buffer);
  80147. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80148. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80149. var dy = 1 / texSize;
  80150. var fy = 0;
  80151. for (var y = 0; y < texSize; y++) {
  80152. var xv1 = faceData[0];
  80153. var xv2 = faceData[2];
  80154. for (var x = 0; x < texSize; x++) {
  80155. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80156. v.normalize();
  80157. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80158. // 3 channels per pixels
  80159. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80160. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80161. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80162. xv1 = xv1.add(rotDX1);
  80163. xv2 = xv2.add(rotDX2);
  80164. }
  80165. fy += dy;
  80166. }
  80167. return textureArray;
  80168. };
  80169. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80170. var theta = Math.atan2(vDir.z, vDir.x);
  80171. var phi = Math.acos(vDir.y);
  80172. while (theta < -Math.PI)
  80173. theta += 2 * Math.PI;
  80174. while (theta > Math.PI)
  80175. theta -= 2 * Math.PI;
  80176. var dx = theta / Math.PI;
  80177. var dy = phi / Math.PI;
  80178. // recenter.
  80179. dx = dx * 0.5 + 0.5;
  80180. var px = Math.round(dx * inputWidth);
  80181. if (px < 0)
  80182. px = 0;
  80183. else if (px >= inputWidth)
  80184. px = inputWidth - 1;
  80185. var py = Math.round(dy * inputHeight);
  80186. if (py < 0)
  80187. py = 0;
  80188. else if (py >= inputHeight)
  80189. py = inputHeight - 1;
  80190. var inputY = (inputHeight - py - 1);
  80191. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80192. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80193. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80194. return {
  80195. r: r,
  80196. g: g,
  80197. b: b
  80198. };
  80199. };
  80200. PanoramaToCubeMapTools.FACE_FRONT = [
  80201. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80202. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80203. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80204. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80205. ];
  80206. PanoramaToCubeMapTools.FACE_BACK = [
  80207. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80208. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80209. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80210. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80211. ];
  80212. PanoramaToCubeMapTools.FACE_RIGHT = [
  80213. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80214. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80215. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80216. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80217. ];
  80218. PanoramaToCubeMapTools.FACE_LEFT = [
  80219. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80220. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80221. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80222. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80223. ];
  80224. PanoramaToCubeMapTools.FACE_DOWN = [
  80225. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80226. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80227. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80228. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80229. ];
  80230. PanoramaToCubeMapTools.FACE_UP = [
  80231. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80232. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80233. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80234. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80235. ];
  80236. return PanoramaToCubeMapTools;
  80237. }());
  80238. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80239. })(BABYLON || (BABYLON = {}));
  80240. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80241. var BABYLON;
  80242. (function (BABYLON) {
  80243. ;
  80244. /**
  80245. * This groups tools to convert HDR texture to native colors array.
  80246. */
  80247. var HDRTools = /** @class */ (function () {
  80248. function HDRTools() {
  80249. }
  80250. HDRTools.Ldexp = function (mantissa, exponent) {
  80251. if (exponent > 1023) {
  80252. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80253. }
  80254. if (exponent < -1074) {
  80255. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80256. }
  80257. return mantissa * Math.pow(2, exponent);
  80258. };
  80259. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80260. if (exponent > 0) { /*nonzero pixel*/
  80261. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80262. float32array[index + 0] = red * exponent;
  80263. float32array[index + 1] = green * exponent;
  80264. float32array[index + 2] = blue * exponent;
  80265. }
  80266. else {
  80267. float32array[index + 0] = 0;
  80268. float32array[index + 1] = 0;
  80269. float32array[index + 2] = 0;
  80270. }
  80271. };
  80272. HDRTools.readStringLine = function (uint8array, startIndex) {
  80273. var line = "";
  80274. var character = "";
  80275. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80276. character = String.fromCharCode(uint8array[i]);
  80277. if (character == "\n") {
  80278. break;
  80279. }
  80280. line += character;
  80281. }
  80282. return line;
  80283. };
  80284. /**
  80285. * Reads header information from an RGBE texture stored in a native array.
  80286. * More information on this format are available here:
  80287. * https://en.wikipedia.org/wiki/RGBE_image_format
  80288. *
  80289. * @param uint8array The binary file stored in native array.
  80290. * @return The header information.
  80291. */
  80292. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80293. var height = 0;
  80294. var width = 0;
  80295. var line = this.readStringLine(uint8array, 0);
  80296. if (line[0] != '#' || line[1] != '?') {
  80297. throw "Bad HDR Format.";
  80298. }
  80299. var endOfHeader = false;
  80300. var findFormat = false;
  80301. var lineIndex = 0;
  80302. do {
  80303. lineIndex += (line.length + 1);
  80304. line = this.readStringLine(uint8array, lineIndex);
  80305. if (line == "FORMAT=32-bit_rle_rgbe") {
  80306. findFormat = true;
  80307. }
  80308. else if (line.length == 0) {
  80309. endOfHeader = true;
  80310. }
  80311. } while (!endOfHeader);
  80312. if (!findFormat) {
  80313. throw "HDR Bad header format, unsupported FORMAT";
  80314. }
  80315. lineIndex += (line.length + 1);
  80316. line = this.readStringLine(uint8array, lineIndex);
  80317. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80318. var match = sizeRegexp.exec(line);
  80319. // TODO. Support +Y and -X if needed.
  80320. if (!match || match.length < 3) {
  80321. throw "HDR Bad header format, no size";
  80322. }
  80323. width = parseInt(match[2]);
  80324. height = parseInt(match[1]);
  80325. if (width < 8 || width > 0x7fff) {
  80326. throw "HDR Bad header format, unsupported size";
  80327. }
  80328. lineIndex += (line.length + 1);
  80329. return {
  80330. height: height,
  80331. width: width,
  80332. dataPosition: lineIndex
  80333. };
  80334. };
  80335. /**
  80336. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80337. * This RGBE texture needs to store the information as a panorama.
  80338. *
  80339. * More information on this format are available here:
  80340. * https://en.wikipedia.org/wiki/RGBE_image_format
  80341. *
  80342. * @param buffer The binary file stored in an array buffer.
  80343. * @param size The expected size of the extracted cubemap.
  80344. * @return The Cube Map information.
  80345. */
  80346. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80347. var uint8array = new Uint8Array(buffer);
  80348. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80349. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80350. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80351. return cubeMapData;
  80352. };
  80353. /**
  80354. * Returns the pixels data extracted from an RGBE texture.
  80355. * This pixels will be stored left to right up to down in the R G B order in one array.
  80356. *
  80357. * More information on this format are available here:
  80358. * https://en.wikipedia.org/wiki/RGBE_image_format
  80359. *
  80360. * @param uint8array The binary file stored in an array buffer.
  80361. * @param hdrInfo The header information of the file.
  80362. * @return The pixels data in RGB right to left up to down order.
  80363. */
  80364. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80365. // Keep for multi format supports.
  80366. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80367. };
  80368. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80369. var num_scanlines = hdrInfo.height;
  80370. var scanline_width = hdrInfo.width;
  80371. var a, b, c, d, count;
  80372. var dataIndex = hdrInfo.dataPosition;
  80373. var index = 0, endIndex = 0, i = 0;
  80374. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80375. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80376. // 3 channels of 4 bytes per pixel in float.
  80377. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80378. var resultArray = new Float32Array(resultBuffer);
  80379. // read in each successive scanline
  80380. while (num_scanlines > 0) {
  80381. a = uint8array[dataIndex++];
  80382. b = uint8array[dataIndex++];
  80383. c = uint8array[dataIndex++];
  80384. d = uint8array[dataIndex++];
  80385. if (a != 2 || b != 2 || (c & 0x80)) {
  80386. // this file is not run length encoded
  80387. throw "HDR Bad header format, not RLE";
  80388. }
  80389. if (((c << 8) | d) != scanline_width) {
  80390. throw "HDR Bad header format, wrong scan line width";
  80391. }
  80392. index = 0;
  80393. // read each of the four channels for the scanline into the buffer
  80394. for (i = 0; i < 4; i++) {
  80395. endIndex = (i + 1) * scanline_width;
  80396. while (index < endIndex) {
  80397. a = uint8array[dataIndex++];
  80398. b = uint8array[dataIndex++];
  80399. if (a > 128) {
  80400. // a run of the same value
  80401. count = a - 128;
  80402. if ((count == 0) || (count > endIndex - index)) {
  80403. throw "HDR Bad Format, bad scanline data (run)";
  80404. }
  80405. while (count-- > 0) {
  80406. scanLineArray[index++] = b;
  80407. }
  80408. }
  80409. else {
  80410. // a non-run
  80411. count = a;
  80412. if ((count == 0) || (count > endIndex - index)) {
  80413. throw "HDR Bad Format, bad scanline data (non-run)";
  80414. }
  80415. scanLineArray[index++] = b;
  80416. if (--count > 0) {
  80417. for (var j = 0; j < count; j++) {
  80418. scanLineArray[index++] = uint8array[dataIndex++];
  80419. }
  80420. }
  80421. }
  80422. }
  80423. }
  80424. // now convert data from buffer into floats
  80425. for (i = 0; i < scanline_width; i++) {
  80426. a = scanLineArray[i];
  80427. b = scanLineArray[i + scanline_width];
  80428. c = scanLineArray[i + 2 * scanline_width];
  80429. d = scanLineArray[i + 3 * scanline_width];
  80430. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80431. }
  80432. num_scanlines--;
  80433. }
  80434. return resultArray;
  80435. };
  80436. return HDRTools;
  80437. }());
  80438. BABYLON.HDRTools = HDRTools;
  80439. })(BABYLON || (BABYLON = {}));
  80440. //# sourceMappingURL=babylon.hdr.js.map
  80441. var BABYLON;
  80442. (function (BABYLON) {
  80443. /**
  80444. * This represents a texture coming from an HDR input.
  80445. *
  80446. * The only supported format is currently panorama picture stored in RGBE format.
  80447. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80448. */
  80449. var HDRCubeTexture = /** @class */ (function (_super) {
  80450. __extends(HDRCubeTexture, _super);
  80451. /**
  80452. * Instantiates an HDRTexture from the following parameters.
  80453. *
  80454. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80455. * @param scene The scene the texture will be used in
  80456. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80457. * @param noMipmap Forces to not generate the mipmap if true
  80458. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80459. * @param gammaSpace 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)
  80460. * @param reserved Reserved flag for internal use.
  80461. */
  80462. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80463. if (noMipmap === void 0) { noMipmap = false; }
  80464. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80465. if (gammaSpace === void 0) { gammaSpace = false; }
  80466. if (reserved === void 0) { reserved = false; }
  80467. if (onLoad === void 0) { onLoad = null; }
  80468. if (onError === void 0) { onError = null; }
  80469. var _this = _super.call(this, scene) || this;
  80470. _this._generateHarmonics = true;
  80471. _this._onLoad = null;
  80472. _this._onError = null;
  80473. /**
  80474. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80475. */
  80476. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80477. _this._isBlocking = true;
  80478. _this._rotationY = 0;
  80479. /**
  80480. * Gets or sets the center of the bounding box associated with the cube texture
  80481. * It must define where the camera used to render the texture was set
  80482. */
  80483. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80484. if (!url) {
  80485. return _this;
  80486. }
  80487. _this.name = url;
  80488. _this.url = url;
  80489. _this.hasAlpha = false;
  80490. _this.isCube = true;
  80491. _this._textureMatrix = BABYLON.Matrix.Identity();
  80492. _this._onLoad = onLoad;
  80493. _this._onError = onError;
  80494. _this.gammaSpace = gammaSpace;
  80495. _this._noMipmap = noMipmap;
  80496. _this._size = size;
  80497. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80498. if (!_this._texture) {
  80499. if (!scene.useDelayedTextureLoading) {
  80500. _this.loadTexture();
  80501. }
  80502. else {
  80503. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80504. }
  80505. }
  80506. return _this;
  80507. }
  80508. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80509. /**
  80510. * Gets wether or not the texture is blocking during loading.
  80511. */
  80512. get: function () {
  80513. return this._isBlocking;
  80514. },
  80515. /**
  80516. * Sets wether or not the texture is blocking during loading.
  80517. */
  80518. set: function (value) {
  80519. this._isBlocking = value;
  80520. },
  80521. enumerable: true,
  80522. configurable: true
  80523. });
  80524. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80525. /**
  80526. * Gets texture matrix rotation angle around Y axis radians.
  80527. */
  80528. get: function () {
  80529. return this._rotationY;
  80530. },
  80531. /**
  80532. * Sets texture matrix rotation angle around Y axis in radians.
  80533. */
  80534. set: function (value) {
  80535. this._rotationY = value;
  80536. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80537. },
  80538. enumerable: true,
  80539. configurable: true
  80540. });
  80541. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80542. get: function () {
  80543. return this._boundingBoxSize;
  80544. },
  80545. /**
  80546. * Gets or sets the size of the bounding box associated with the cube texture
  80547. * When defined, the cubemap will switch to local mode
  80548. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80549. * @example https://www.babylonjs-playground.com/#RNASML
  80550. */
  80551. set: function (value) {
  80552. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80553. return;
  80554. }
  80555. this._boundingBoxSize = value;
  80556. var scene = this.getScene();
  80557. if (scene) {
  80558. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80559. }
  80560. },
  80561. enumerable: true,
  80562. configurable: true
  80563. });
  80564. /**
  80565. * Occurs when the file is raw .hdr file.
  80566. */
  80567. HDRCubeTexture.prototype.loadTexture = function () {
  80568. var _this = this;
  80569. var callback = function (buffer) {
  80570. var scene = _this.getScene();
  80571. if (!scene) {
  80572. return null;
  80573. }
  80574. // Extract the raw linear data.
  80575. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80576. // Generate harmonics if needed.
  80577. if (_this._generateHarmonics) {
  80578. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80579. _this.sphericalPolynomial = sphericalPolynomial;
  80580. }
  80581. var results = [];
  80582. var byteArray = null;
  80583. // Push each faces.
  80584. for (var j = 0; j < 6; j++) {
  80585. // Create uintarray fallback.
  80586. if (!scene.getEngine().getCaps().textureFloat) {
  80587. // 3 channels of 1 bytes per pixel in bytes.
  80588. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80589. byteArray = new Uint8Array(byteBuffer);
  80590. }
  80591. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80592. // If special cases.
  80593. if (_this.gammaSpace || byteArray) {
  80594. for (var i = 0; i < _this._size * _this._size; i++) {
  80595. // Put in gamma space if requested.
  80596. if (_this.gammaSpace) {
  80597. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80598. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80599. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80600. }
  80601. // Convert to int texture for fallback.
  80602. if (byteArray) {
  80603. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80604. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80605. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80606. // May use luminance instead if the result is not accurate.
  80607. var max = Math.max(Math.max(r, g), b);
  80608. if (max > 255) {
  80609. var scale = 255 / max;
  80610. r *= scale;
  80611. g *= scale;
  80612. b *= scale;
  80613. }
  80614. byteArray[(i * 3) + 0] = r;
  80615. byteArray[(i * 3) + 1] = g;
  80616. byteArray[(i * 3) + 2] = b;
  80617. }
  80618. }
  80619. }
  80620. if (byteArray) {
  80621. results.push(byteArray);
  80622. }
  80623. else {
  80624. results.push(dataFace);
  80625. }
  80626. }
  80627. return results;
  80628. };
  80629. var scene = this.getScene();
  80630. if (scene) {
  80631. 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, null, this._onLoad, this._onError);
  80632. }
  80633. };
  80634. HDRCubeTexture.prototype.clone = function () {
  80635. var scene = this.getScene();
  80636. if (!scene) {
  80637. return this;
  80638. }
  80639. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80640. // Base texture
  80641. newTexture.level = this.level;
  80642. newTexture.wrapU = this.wrapU;
  80643. newTexture.wrapV = this.wrapV;
  80644. newTexture.coordinatesIndex = this.coordinatesIndex;
  80645. newTexture.coordinatesMode = this.coordinatesMode;
  80646. return newTexture;
  80647. };
  80648. // Methods
  80649. HDRCubeTexture.prototype.delayLoad = function () {
  80650. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80651. return;
  80652. }
  80653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80654. this._texture = this._getFromCache(this.url, this._noMipmap);
  80655. if (!this._texture) {
  80656. this.loadTexture();
  80657. }
  80658. };
  80659. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80660. return this._textureMatrix;
  80661. };
  80662. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80663. this._textureMatrix = value;
  80664. };
  80665. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80666. var texture = null;
  80667. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80668. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80669. texture.name = parsedTexture.name;
  80670. texture.hasAlpha = parsedTexture.hasAlpha;
  80671. texture.level = parsedTexture.level;
  80672. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80673. texture.isBlocking = parsedTexture.isBlocking;
  80674. }
  80675. if (texture) {
  80676. if (parsedTexture.boundingBoxPosition) {
  80677. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80678. }
  80679. if (parsedTexture.boundingBoxSize) {
  80680. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80681. }
  80682. if (parsedTexture.rotationY) {
  80683. texture.rotationY = parsedTexture.rotationY;
  80684. }
  80685. }
  80686. return texture;
  80687. };
  80688. HDRCubeTexture.prototype.serialize = function () {
  80689. if (!this.name) {
  80690. return null;
  80691. }
  80692. var serializationObject = {};
  80693. serializationObject.name = this.name;
  80694. serializationObject.hasAlpha = this.hasAlpha;
  80695. serializationObject.isCube = true;
  80696. serializationObject.level = this.level;
  80697. serializationObject.size = this._size;
  80698. serializationObject.coordinatesMode = this.coordinatesMode;
  80699. serializationObject.useInGammaSpace = this.gammaSpace;
  80700. serializationObject.generateHarmonics = this._generateHarmonics;
  80701. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80702. serializationObject.noMipmap = this._noMipmap;
  80703. serializationObject.isBlocking = this._isBlocking;
  80704. serializationObject.rotationY = this._rotationY;
  80705. return serializationObject;
  80706. };
  80707. HDRCubeTexture._facesMapping = [
  80708. "right",
  80709. "left",
  80710. "up",
  80711. "down",
  80712. "front",
  80713. "back"
  80714. ];
  80715. return HDRCubeTexture;
  80716. }(BABYLON.BaseTexture));
  80717. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80718. })(BABYLON || (BABYLON = {}));
  80719. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80720. var BABYLON;
  80721. (function (BABYLON) {
  80722. var IndexedVector2 = /** @class */ (function (_super) {
  80723. __extends(IndexedVector2, _super);
  80724. function IndexedVector2(original, index) {
  80725. var _this = _super.call(this, original.x, original.y) || this;
  80726. _this.index = index;
  80727. return _this;
  80728. }
  80729. return IndexedVector2;
  80730. }(BABYLON.Vector2));
  80731. var PolygonPoints = /** @class */ (function () {
  80732. function PolygonPoints() {
  80733. this.elements = new Array();
  80734. }
  80735. PolygonPoints.prototype.add = function (originalPoints) {
  80736. var _this = this;
  80737. var result = new Array();
  80738. originalPoints.forEach(function (point) {
  80739. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80740. var newPoint = new IndexedVector2(point, _this.elements.length);
  80741. result.push(newPoint);
  80742. _this.elements.push(newPoint);
  80743. }
  80744. });
  80745. return result;
  80746. };
  80747. PolygonPoints.prototype.computeBounds = function () {
  80748. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80749. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80750. this.elements.forEach(function (point) {
  80751. // x
  80752. if (point.x < lmin.x) {
  80753. lmin.x = point.x;
  80754. }
  80755. else if (point.x > lmax.x) {
  80756. lmax.x = point.x;
  80757. }
  80758. // y
  80759. if (point.y < lmin.y) {
  80760. lmin.y = point.y;
  80761. }
  80762. else if (point.y > lmax.y) {
  80763. lmax.y = point.y;
  80764. }
  80765. });
  80766. return {
  80767. min: lmin,
  80768. max: lmax,
  80769. width: lmax.x - lmin.x,
  80770. height: lmax.y - lmin.y
  80771. };
  80772. };
  80773. return PolygonPoints;
  80774. }());
  80775. var Polygon = /** @class */ (function () {
  80776. function Polygon() {
  80777. }
  80778. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80779. return [
  80780. new BABYLON.Vector2(xmin, ymin),
  80781. new BABYLON.Vector2(xmax, ymin),
  80782. new BABYLON.Vector2(xmax, ymax),
  80783. new BABYLON.Vector2(xmin, ymax)
  80784. ];
  80785. };
  80786. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80787. if (cx === void 0) { cx = 0; }
  80788. if (cy === void 0) { cy = 0; }
  80789. if (numberOfSides === void 0) { numberOfSides = 32; }
  80790. var result = new Array();
  80791. var angle = 0;
  80792. var increment = (Math.PI * 2) / numberOfSides;
  80793. for (var i = 0; i < numberOfSides; i++) {
  80794. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80795. angle -= increment;
  80796. }
  80797. return result;
  80798. };
  80799. Polygon.Parse = function (input) {
  80800. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80801. var i, result = [];
  80802. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80803. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80804. }
  80805. return result;
  80806. };
  80807. Polygon.StartingAt = function (x, y) {
  80808. return BABYLON.Path2.StartingAt(x, y);
  80809. };
  80810. return Polygon;
  80811. }());
  80812. BABYLON.Polygon = Polygon;
  80813. var PolygonMeshBuilder = /** @class */ (function () {
  80814. function PolygonMeshBuilder(name, contours, scene) {
  80815. this._points = new PolygonPoints();
  80816. this._outlinepoints = new PolygonPoints();
  80817. this._holes = new Array();
  80818. this._epoints = new Array();
  80819. this._eholes = new Array();
  80820. this._name = name;
  80821. this._scene = scene;
  80822. var points;
  80823. if (contours instanceof BABYLON.Path2) {
  80824. points = contours.getPoints();
  80825. }
  80826. else {
  80827. points = contours;
  80828. }
  80829. this._addToepoint(points);
  80830. this._points.add(points);
  80831. this._outlinepoints.add(points);
  80832. if (typeof earcut === 'undefined') {
  80833. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80834. }
  80835. }
  80836. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80837. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80838. var p = points_1[_i];
  80839. this._epoints.push(p.x, p.y);
  80840. }
  80841. };
  80842. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80843. this._points.add(hole);
  80844. var holepoints = new PolygonPoints();
  80845. holepoints.add(hole);
  80846. this._holes.push(holepoints);
  80847. this._eholes.push(this._epoints.length / 2);
  80848. this._addToepoint(hole);
  80849. return this;
  80850. };
  80851. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80852. var _this = this;
  80853. if (updatable === void 0) { updatable = false; }
  80854. if (depth === void 0) { depth = 0; }
  80855. var result = new BABYLON.Mesh(this._name, this._scene);
  80856. var normals = new Array();
  80857. var positions = new Array();
  80858. var uvs = new Array();
  80859. var bounds = this._points.computeBounds();
  80860. this._points.elements.forEach(function (p) {
  80861. normals.push(0, 1.0, 0);
  80862. positions.push(p.x, 0, p.y);
  80863. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80864. });
  80865. var indices = new Array();
  80866. var res = earcut(this._epoints, this._eholes, 2);
  80867. for (var i = 0; i < res.length; i++) {
  80868. indices.push(res[i]);
  80869. }
  80870. if (depth > 0) {
  80871. var positionscount = (positions.length / 3); //get the current pointcount
  80872. this._points.elements.forEach(function (p) {
  80873. normals.push(0, -1.0, 0);
  80874. positions.push(p.x, -depth, p.y);
  80875. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80876. });
  80877. var totalCount = indices.length;
  80878. for (var i = 0; i < totalCount; i += 3) {
  80879. var i0 = indices[i + 0];
  80880. var i1 = indices[i + 1];
  80881. var i2 = indices[i + 2];
  80882. indices.push(i2 + positionscount);
  80883. indices.push(i1 + positionscount);
  80884. indices.push(i0 + positionscount);
  80885. }
  80886. //Add the sides
  80887. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80888. this._holes.forEach(function (hole) {
  80889. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80890. });
  80891. }
  80892. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80893. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80894. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80895. result.setIndices(indices);
  80896. return result;
  80897. };
  80898. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80899. var StartIndex = positions.length / 3;
  80900. var ulength = 0;
  80901. for (var i = 0; i < points.elements.length; i++) {
  80902. var p = points.elements[i];
  80903. var p1;
  80904. if ((i + 1) > points.elements.length - 1) {
  80905. p1 = points.elements[0];
  80906. }
  80907. else {
  80908. p1 = points.elements[i + 1];
  80909. }
  80910. positions.push(p.x, 0, p.y);
  80911. positions.push(p.x, -depth, p.y);
  80912. positions.push(p1.x, 0, p1.y);
  80913. positions.push(p1.x, -depth, p1.y);
  80914. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80915. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80916. var v3 = v2.subtract(v1);
  80917. var v4 = new BABYLON.Vector3(0, 1, 0);
  80918. var vn = BABYLON.Vector3.Cross(v3, v4);
  80919. vn = vn.normalize();
  80920. uvs.push(ulength / bounds.width, 0);
  80921. uvs.push(ulength / bounds.width, 1);
  80922. ulength += v3.length();
  80923. uvs.push((ulength / bounds.width), 0);
  80924. uvs.push((ulength / bounds.width), 1);
  80925. if (!flip) {
  80926. normals.push(-vn.x, -vn.y, -vn.z);
  80927. normals.push(-vn.x, -vn.y, -vn.z);
  80928. normals.push(-vn.x, -vn.y, -vn.z);
  80929. normals.push(-vn.x, -vn.y, -vn.z);
  80930. indices.push(StartIndex);
  80931. indices.push(StartIndex + 1);
  80932. indices.push(StartIndex + 2);
  80933. indices.push(StartIndex + 1);
  80934. indices.push(StartIndex + 3);
  80935. indices.push(StartIndex + 2);
  80936. }
  80937. else {
  80938. normals.push(vn.x, vn.y, vn.z);
  80939. normals.push(vn.x, vn.y, vn.z);
  80940. normals.push(vn.x, vn.y, vn.z);
  80941. normals.push(vn.x, vn.y, vn.z);
  80942. indices.push(StartIndex);
  80943. indices.push(StartIndex + 2);
  80944. indices.push(StartIndex + 1);
  80945. indices.push(StartIndex + 1);
  80946. indices.push(StartIndex + 2);
  80947. indices.push(StartIndex + 3);
  80948. }
  80949. StartIndex += 4;
  80950. }
  80951. ;
  80952. };
  80953. return PolygonMeshBuilder;
  80954. }());
  80955. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80956. })(BABYLON || (BABYLON = {}));
  80957. //# sourceMappingURL=babylon.polygonMesh.js.map
  80958. var BABYLON;
  80959. (function (BABYLON) {
  80960. // Unique ID when we import meshes from Babylon to CSG
  80961. var currentCSGMeshId = 0;
  80962. // # class Vertex
  80963. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80964. // one to provide additional features like texture coordinates and vertex
  80965. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80966. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80967. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80968. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80969. // is not used anywhere else.
  80970. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80971. var Vertex = /** @class */ (function () {
  80972. function Vertex(pos, normal, uv) {
  80973. this.pos = pos;
  80974. this.normal = normal;
  80975. this.uv = uv;
  80976. }
  80977. Vertex.prototype.clone = function () {
  80978. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80979. };
  80980. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80981. // orientation of a polygon is flipped.
  80982. Vertex.prototype.flip = function () {
  80983. this.normal = this.normal.scale(-1);
  80984. };
  80985. // Create a new vertex between this vertex and `other` by linearly
  80986. // interpolating all properties using a parameter of `t`. Subclasses should
  80987. // override this to interpolate additional properties.
  80988. Vertex.prototype.interpolate = function (other, t) {
  80989. 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));
  80990. };
  80991. return Vertex;
  80992. }());
  80993. // # class Plane
  80994. // Represents a plane in 3D space.
  80995. var Plane = /** @class */ (function () {
  80996. function Plane(normal, w) {
  80997. this.normal = normal;
  80998. this.w = w;
  80999. }
  81000. Plane.FromPoints = function (a, b, c) {
  81001. var v0 = c.subtract(a);
  81002. var v1 = b.subtract(a);
  81003. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81004. return null;
  81005. }
  81006. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81007. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81008. };
  81009. Plane.prototype.clone = function () {
  81010. return new Plane(this.normal.clone(), this.w);
  81011. };
  81012. Plane.prototype.flip = function () {
  81013. this.normal.scaleInPlace(-1);
  81014. this.w = -this.w;
  81015. };
  81016. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81017. // fragments in the appropriate lists. Coplanar polygons go into either
  81018. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81019. // respect to this plane. Polygons in front or in back of this plane go into
  81020. // either `front` or `back`.
  81021. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81022. var COPLANAR = 0;
  81023. var FRONT = 1;
  81024. var BACK = 2;
  81025. var SPANNING = 3;
  81026. // Classify each point as well as the entire polygon into one of the above
  81027. // four classes.
  81028. var polygonType = 0;
  81029. var types = [];
  81030. var i;
  81031. var t;
  81032. for (i = 0; i < polygon.vertices.length; i++) {
  81033. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81034. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81035. polygonType |= type;
  81036. types.push(type);
  81037. }
  81038. // Put the polygon in the correct list, splitting it when necessary.
  81039. switch (polygonType) {
  81040. case COPLANAR:
  81041. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81042. break;
  81043. case FRONT:
  81044. front.push(polygon);
  81045. break;
  81046. case BACK:
  81047. back.push(polygon);
  81048. break;
  81049. case SPANNING:
  81050. var f = [], b = [];
  81051. for (i = 0; i < polygon.vertices.length; i++) {
  81052. var j = (i + 1) % polygon.vertices.length;
  81053. var ti = types[i], tj = types[j];
  81054. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81055. if (ti !== BACK)
  81056. f.push(vi);
  81057. if (ti !== FRONT)
  81058. b.push(ti !== BACK ? vi.clone() : vi);
  81059. if ((ti | tj) === SPANNING) {
  81060. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81061. var v = vi.interpolate(vj, t);
  81062. f.push(v);
  81063. b.push(v.clone());
  81064. }
  81065. }
  81066. var poly;
  81067. if (f.length >= 3) {
  81068. poly = new Polygon(f, polygon.shared);
  81069. if (poly.plane)
  81070. front.push(poly);
  81071. }
  81072. if (b.length >= 3) {
  81073. poly = new Polygon(b, polygon.shared);
  81074. if (poly.plane)
  81075. back.push(poly);
  81076. }
  81077. break;
  81078. }
  81079. };
  81080. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81081. // point is on the plane.
  81082. Plane.EPSILON = 1e-5;
  81083. return Plane;
  81084. }());
  81085. // # class Polygon
  81086. // Represents a convex polygon. The vertices used to initialize a polygon must
  81087. // be coplanar and form a convex loop.
  81088. //
  81089. // Each convex polygon has a `shared` property, which is shared between all
  81090. // polygons that are clones of each other or were split from the same polygon.
  81091. // This can be used to define per-polygon properties (such as surface color).
  81092. var Polygon = /** @class */ (function () {
  81093. function Polygon(vertices, shared) {
  81094. this.vertices = vertices;
  81095. this.shared = shared;
  81096. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81097. }
  81098. Polygon.prototype.clone = function () {
  81099. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81100. return new Polygon(vertices, this.shared);
  81101. };
  81102. Polygon.prototype.flip = function () {
  81103. this.vertices.reverse().map(function (v) { v.flip(); });
  81104. this.plane.flip();
  81105. };
  81106. return Polygon;
  81107. }());
  81108. // # class Node
  81109. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81110. // by picking a polygon to split along. That polygon (and all other coplanar
  81111. // polygons) are added directly to that node and the other polygons are added to
  81112. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81113. // no distinction between internal and leaf nodes.
  81114. var Node = /** @class */ (function () {
  81115. function Node(polygons) {
  81116. this.plane = null;
  81117. this.front = null;
  81118. this.back = null;
  81119. this.polygons = new Array();
  81120. if (polygons) {
  81121. this.build(polygons);
  81122. }
  81123. }
  81124. Node.prototype.clone = function () {
  81125. var node = new Node();
  81126. node.plane = this.plane && this.plane.clone();
  81127. node.front = this.front && this.front.clone();
  81128. node.back = this.back && this.back.clone();
  81129. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81130. return node;
  81131. };
  81132. // Convert solid space to empty space and empty space to solid space.
  81133. Node.prototype.invert = function () {
  81134. for (var i = 0; i < this.polygons.length; i++) {
  81135. this.polygons[i].flip();
  81136. }
  81137. if (this.plane) {
  81138. this.plane.flip();
  81139. }
  81140. if (this.front) {
  81141. this.front.invert();
  81142. }
  81143. if (this.back) {
  81144. this.back.invert();
  81145. }
  81146. var temp = this.front;
  81147. this.front = this.back;
  81148. this.back = temp;
  81149. };
  81150. // Recursively remove all polygons in `polygons` that are inside this BSP
  81151. // tree.
  81152. Node.prototype.clipPolygons = function (polygons) {
  81153. if (!this.plane)
  81154. return polygons.slice();
  81155. var front = new Array(), back = new Array();
  81156. for (var i = 0; i < polygons.length; i++) {
  81157. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81158. }
  81159. if (this.front) {
  81160. front = this.front.clipPolygons(front);
  81161. }
  81162. if (this.back) {
  81163. back = this.back.clipPolygons(back);
  81164. }
  81165. else {
  81166. back = [];
  81167. }
  81168. return front.concat(back);
  81169. };
  81170. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81171. // `bsp`.
  81172. Node.prototype.clipTo = function (bsp) {
  81173. this.polygons = bsp.clipPolygons(this.polygons);
  81174. if (this.front)
  81175. this.front.clipTo(bsp);
  81176. if (this.back)
  81177. this.back.clipTo(bsp);
  81178. };
  81179. // Return a list of all polygons in this BSP tree.
  81180. Node.prototype.allPolygons = function () {
  81181. var polygons = this.polygons.slice();
  81182. if (this.front)
  81183. polygons = polygons.concat(this.front.allPolygons());
  81184. if (this.back)
  81185. polygons = polygons.concat(this.back.allPolygons());
  81186. return polygons;
  81187. };
  81188. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81189. // new polygons are filtered down to the bottom of the tree and become new
  81190. // nodes there. Each set of polygons is partitioned using the first polygon
  81191. // (no heuristic is used to pick a good split).
  81192. Node.prototype.build = function (polygons) {
  81193. if (!polygons.length)
  81194. return;
  81195. if (!this.plane)
  81196. this.plane = polygons[0].plane.clone();
  81197. var front = new Array(), back = new Array();
  81198. for (var i = 0; i < polygons.length; i++) {
  81199. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81200. }
  81201. if (front.length) {
  81202. if (!this.front)
  81203. this.front = new Node();
  81204. this.front.build(front);
  81205. }
  81206. if (back.length) {
  81207. if (!this.back)
  81208. this.back = new Node();
  81209. this.back.build(back);
  81210. }
  81211. };
  81212. return Node;
  81213. }());
  81214. var CSG = /** @class */ (function () {
  81215. function CSG() {
  81216. this.polygons = new Array();
  81217. }
  81218. // Convert BABYLON.Mesh to BABYLON.CSG
  81219. CSG.FromMesh = function (mesh) {
  81220. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81221. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81222. if (mesh instanceof BABYLON.Mesh) {
  81223. mesh.computeWorldMatrix(true);
  81224. matrix = mesh.getWorldMatrix();
  81225. meshPosition = mesh.position.clone();
  81226. meshRotation = mesh.rotation.clone();
  81227. if (mesh.rotationQuaternion) {
  81228. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81229. }
  81230. meshScaling = mesh.scaling.clone();
  81231. }
  81232. else {
  81233. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81234. }
  81235. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81236. var subMeshes = mesh.subMeshes;
  81237. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81238. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81239. vertices = [];
  81240. for (var j = 0; j < 3; j++) {
  81241. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81242. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81243. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81244. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81245. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81246. vertex = new Vertex(position, normal, uv);
  81247. vertices.push(vertex);
  81248. }
  81249. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81250. // To handle the case of degenerated triangle
  81251. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81252. if (polygon.plane)
  81253. polygons.push(polygon);
  81254. }
  81255. }
  81256. var csg = CSG.FromPolygons(polygons);
  81257. csg.matrix = matrix;
  81258. csg.position = meshPosition;
  81259. csg.rotation = meshRotation;
  81260. csg.scaling = meshScaling;
  81261. csg.rotationQuaternion = meshRotationQuaternion;
  81262. currentCSGMeshId++;
  81263. return csg;
  81264. };
  81265. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81266. CSG.FromPolygons = function (polygons) {
  81267. var csg = new CSG();
  81268. csg.polygons = polygons;
  81269. return csg;
  81270. };
  81271. CSG.prototype.clone = function () {
  81272. var csg = new CSG();
  81273. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81274. csg.copyTransformAttributes(this);
  81275. return csg;
  81276. };
  81277. CSG.prototype.union = function (csg) {
  81278. var a = new Node(this.clone().polygons);
  81279. var b = new Node(csg.clone().polygons);
  81280. a.clipTo(b);
  81281. b.clipTo(a);
  81282. b.invert();
  81283. b.clipTo(a);
  81284. b.invert();
  81285. a.build(b.allPolygons());
  81286. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81287. };
  81288. CSG.prototype.unionInPlace = function (csg) {
  81289. var a = new Node(this.polygons);
  81290. var b = new Node(csg.polygons);
  81291. a.clipTo(b);
  81292. b.clipTo(a);
  81293. b.invert();
  81294. b.clipTo(a);
  81295. b.invert();
  81296. a.build(b.allPolygons());
  81297. this.polygons = a.allPolygons();
  81298. };
  81299. CSG.prototype.subtract = function (csg) {
  81300. var a = new Node(this.clone().polygons);
  81301. var b = new Node(csg.clone().polygons);
  81302. a.invert();
  81303. a.clipTo(b);
  81304. b.clipTo(a);
  81305. b.invert();
  81306. b.clipTo(a);
  81307. b.invert();
  81308. a.build(b.allPolygons());
  81309. a.invert();
  81310. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81311. };
  81312. CSG.prototype.subtractInPlace = function (csg) {
  81313. var a = new Node(this.polygons);
  81314. var b = new Node(csg.polygons);
  81315. a.invert();
  81316. a.clipTo(b);
  81317. b.clipTo(a);
  81318. b.invert();
  81319. b.clipTo(a);
  81320. b.invert();
  81321. a.build(b.allPolygons());
  81322. a.invert();
  81323. this.polygons = a.allPolygons();
  81324. };
  81325. CSG.prototype.intersect = function (csg) {
  81326. var a = new Node(this.clone().polygons);
  81327. var b = new Node(csg.clone().polygons);
  81328. a.invert();
  81329. b.clipTo(a);
  81330. b.invert();
  81331. a.clipTo(b);
  81332. b.clipTo(a);
  81333. a.build(b.allPolygons());
  81334. a.invert();
  81335. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81336. };
  81337. CSG.prototype.intersectInPlace = function (csg) {
  81338. var a = new Node(this.polygons);
  81339. var b = new Node(csg.polygons);
  81340. a.invert();
  81341. b.clipTo(a);
  81342. b.invert();
  81343. a.clipTo(b);
  81344. b.clipTo(a);
  81345. a.build(b.allPolygons());
  81346. a.invert();
  81347. this.polygons = a.allPolygons();
  81348. };
  81349. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81350. // not modified.
  81351. CSG.prototype.inverse = function () {
  81352. var csg = this.clone();
  81353. csg.inverseInPlace();
  81354. return csg;
  81355. };
  81356. CSG.prototype.inverseInPlace = function () {
  81357. this.polygons.map(function (p) { p.flip(); });
  81358. };
  81359. // This is used to keep meshes transformations so they can be restored
  81360. // when we build back a Babylon Mesh
  81361. // NB : All CSG operations are performed in world coordinates
  81362. CSG.prototype.copyTransformAttributes = function (csg) {
  81363. this.matrix = csg.matrix;
  81364. this.position = csg.position;
  81365. this.rotation = csg.rotation;
  81366. this.scaling = csg.scaling;
  81367. this.rotationQuaternion = csg.rotationQuaternion;
  81368. return this;
  81369. };
  81370. // Build Raw mesh from CSG
  81371. // Coordinates here are in world space
  81372. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81373. var matrix = this.matrix.clone();
  81374. matrix.invert();
  81375. 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;
  81376. if (keepSubMeshes) {
  81377. // Sort Polygons, since subMeshes are indices range
  81378. polygons.sort(function (a, b) {
  81379. if (a.shared.meshId === b.shared.meshId) {
  81380. return a.shared.subMeshId - b.shared.subMeshId;
  81381. }
  81382. else {
  81383. return a.shared.meshId - b.shared.meshId;
  81384. }
  81385. });
  81386. }
  81387. for (var i = 0, il = polygons.length; i < il; i++) {
  81388. polygon = polygons[i];
  81389. // Building SubMeshes
  81390. if (!subMesh_dict[polygon.shared.meshId]) {
  81391. subMesh_dict[polygon.shared.meshId] = {};
  81392. }
  81393. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81394. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81395. indexStart: +Infinity,
  81396. indexEnd: -Infinity,
  81397. materialIndex: polygon.shared.materialIndex
  81398. };
  81399. }
  81400. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81401. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81402. polygonIndices[0] = 0;
  81403. polygonIndices[1] = j - 1;
  81404. polygonIndices[2] = j;
  81405. for (var k = 0; k < 3; k++) {
  81406. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81407. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81408. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81409. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81410. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81411. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81412. // Check if 2 points can be merged
  81413. if (!(typeof vertex_idx !== 'undefined' &&
  81414. normals[vertex_idx * 3] === localNormal.x &&
  81415. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81416. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81417. uvs[vertex_idx * 2] === uv.x &&
  81418. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81419. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81420. uvs.push(uv.x, uv.y);
  81421. normals.push(normal.x, normal.y, normal.z);
  81422. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81423. }
  81424. indices.push(vertex_idx);
  81425. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81426. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81427. currentIndex++;
  81428. }
  81429. }
  81430. }
  81431. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81432. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81433. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81434. mesh.setIndices(indices, null);
  81435. if (keepSubMeshes) {
  81436. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81437. var materialIndexOffset = 0, materialMaxIndex;
  81438. mesh.subMeshes = new Array();
  81439. for (var m in subMesh_dict) {
  81440. materialMaxIndex = -1;
  81441. for (var sm in subMesh_dict[m]) {
  81442. subMesh_obj = subMesh_dict[m][sm];
  81443. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81444. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81445. }
  81446. materialIndexOffset += ++materialMaxIndex;
  81447. }
  81448. }
  81449. return mesh;
  81450. };
  81451. // Build Mesh from CSG taking material and transforms into account
  81452. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81453. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81454. mesh.material = material;
  81455. mesh.position.copyFrom(this.position);
  81456. mesh.rotation.copyFrom(this.rotation);
  81457. if (this.rotationQuaternion) {
  81458. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81459. }
  81460. mesh.scaling.copyFrom(this.scaling);
  81461. mesh.computeWorldMatrix(true);
  81462. return mesh;
  81463. };
  81464. return CSG;
  81465. }());
  81466. BABYLON.CSG = CSG;
  81467. })(BABYLON || (BABYLON = {}));
  81468. //# sourceMappingURL=babylon.csg.js.map
  81469. var BABYLON;
  81470. (function (BABYLON) {
  81471. var LensFlare = /** @class */ (function () {
  81472. function LensFlare(size, position, color, imgUrl, system) {
  81473. this.size = size;
  81474. this.position = position;
  81475. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81476. this.color = color || new BABYLON.Color3(1, 1, 1);
  81477. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81478. this._system = system;
  81479. system.lensFlares.push(this);
  81480. }
  81481. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81482. return new LensFlare(size, position, color, imgUrl, system);
  81483. };
  81484. LensFlare.prototype.dispose = function () {
  81485. if (this.texture) {
  81486. this.texture.dispose();
  81487. }
  81488. // Remove from scene
  81489. var index = this._system.lensFlares.indexOf(this);
  81490. this._system.lensFlares.splice(index, 1);
  81491. };
  81492. ;
  81493. return LensFlare;
  81494. }());
  81495. BABYLON.LensFlare = LensFlare;
  81496. })(BABYLON || (BABYLON = {}));
  81497. //# sourceMappingURL=babylon.lensFlare.js.map
  81498. var BABYLON;
  81499. (function (BABYLON) {
  81500. var LensFlareSystem = /** @class */ (function () {
  81501. function LensFlareSystem(name, emitter, scene) {
  81502. this.name = name;
  81503. this.lensFlares = new Array();
  81504. this.borderLimit = 300;
  81505. this.viewportBorder = 0;
  81506. this.layerMask = 0x0FFFFFFF;
  81507. this._vertexBuffers = {};
  81508. this._isEnabled = true;
  81509. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81510. this._emitter = emitter;
  81511. this.id = name;
  81512. scene.lensFlareSystems.push(this);
  81513. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81514. var engine = scene.getEngine();
  81515. // VBO
  81516. var vertices = [];
  81517. vertices.push(1, 1);
  81518. vertices.push(-1, 1);
  81519. vertices.push(-1, -1);
  81520. vertices.push(1, -1);
  81521. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81522. // Indices
  81523. var indices = [];
  81524. indices.push(0);
  81525. indices.push(1);
  81526. indices.push(2);
  81527. indices.push(0);
  81528. indices.push(2);
  81529. indices.push(3);
  81530. this._indexBuffer = engine.createIndexBuffer(indices);
  81531. // Effects
  81532. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81533. }
  81534. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81535. get: function () {
  81536. return this._isEnabled;
  81537. },
  81538. set: function (value) {
  81539. this._isEnabled = value;
  81540. },
  81541. enumerable: true,
  81542. configurable: true
  81543. });
  81544. LensFlareSystem.prototype.getScene = function () {
  81545. return this._scene;
  81546. };
  81547. LensFlareSystem.prototype.getEmitter = function () {
  81548. return this._emitter;
  81549. };
  81550. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81551. this._emitter = newEmitter;
  81552. };
  81553. LensFlareSystem.prototype.getEmitterPosition = function () {
  81554. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81555. };
  81556. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81557. var position = this.getEmitterPosition();
  81558. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81559. this._positionX = position.x;
  81560. this._positionY = position.y;
  81561. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81562. if (this.viewportBorder > 0) {
  81563. globalViewport.x -= this.viewportBorder;
  81564. globalViewport.y -= this.viewportBorder;
  81565. globalViewport.width += this.viewportBorder * 2;
  81566. globalViewport.height += this.viewportBorder * 2;
  81567. position.x += this.viewportBorder;
  81568. position.y += this.viewportBorder;
  81569. this._positionX += this.viewportBorder;
  81570. this._positionY += this.viewportBorder;
  81571. }
  81572. if (position.z > 0) {
  81573. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81574. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81575. return true;
  81576. }
  81577. return true;
  81578. }
  81579. return false;
  81580. };
  81581. LensFlareSystem.prototype._isVisible = function () {
  81582. if (!this._isEnabled || !this._scene.activeCamera) {
  81583. return false;
  81584. }
  81585. var emitterPosition = this.getEmitterPosition();
  81586. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81587. var distance = direction.length();
  81588. direction.normalize();
  81589. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81590. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81591. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81592. };
  81593. LensFlareSystem.prototype.render = function () {
  81594. if (!this._effect.isReady() || !this._scene.activeCamera)
  81595. return false;
  81596. var engine = this._scene.getEngine();
  81597. var viewport = this._scene.activeCamera.viewport;
  81598. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81599. // Position
  81600. if (!this.computeEffectivePosition(globalViewport)) {
  81601. return false;
  81602. }
  81603. // Visibility
  81604. if (!this._isVisible()) {
  81605. return false;
  81606. }
  81607. // Intensity
  81608. var awayX;
  81609. var awayY;
  81610. if (this._positionX < this.borderLimit + globalViewport.x) {
  81611. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81612. }
  81613. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81614. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81615. }
  81616. else {
  81617. awayX = 0;
  81618. }
  81619. if (this._positionY < this.borderLimit + globalViewport.y) {
  81620. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81621. }
  81622. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81623. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81624. }
  81625. else {
  81626. awayY = 0;
  81627. }
  81628. var away = (awayX > awayY) ? awayX : awayY;
  81629. away -= this.viewportBorder;
  81630. if (away > this.borderLimit) {
  81631. away = this.borderLimit;
  81632. }
  81633. var intensity = 1.0 - (away / this.borderLimit);
  81634. if (intensity < 0) {
  81635. return false;
  81636. }
  81637. if (intensity > 1.0) {
  81638. intensity = 1.0;
  81639. }
  81640. if (this.viewportBorder > 0) {
  81641. globalViewport.x += this.viewportBorder;
  81642. globalViewport.y += this.viewportBorder;
  81643. globalViewport.width -= this.viewportBorder * 2;
  81644. globalViewport.height -= this.viewportBorder * 2;
  81645. this._positionX -= this.viewportBorder;
  81646. this._positionY -= this.viewportBorder;
  81647. }
  81648. // Position
  81649. var centerX = globalViewport.x + globalViewport.width / 2;
  81650. var centerY = globalViewport.y + globalViewport.height / 2;
  81651. var distX = centerX - this._positionX;
  81652. var distY = centerY - this._positionY;
  81653. // Effects
  81654. engine.enableEffect(this._effect);
  81655. engine.setState(false);
  81656. engine.setDepthBuffer(false);
  81657. // VBOs
  81658. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81659. // Flares
  81660. for (var index = 0; index < this.lensFlares.length; index++) {
  81661. var flare = this.lensFlares[index];
  81662. engine.setAlphaMode(flare.alphaMode);
  81663. var x = centerX - (distX * flare.position);
  81664. var y = centerY - (distY * flare.position);
  81665. var cw = flare.size;
  81666. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81667. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81668. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81669. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81670. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81671. // Texture
  81672. this._effect.setTexture("textureSampler", flare.texture);
  81673. // Color
  81674. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81675. // Draw order
  81676. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81677. }
  81678. engine.setDepthBuffer(true);
  81679. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81680. return true;
  81681. };
  81682. LensFlareSystem.prototype.dispose = function () {
  81683. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81684. if (vertexBuffer) {
  81685. vertexBuffer.dispose();
  81686. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81687. }
  81688. if (this._indexBuffer) {
  81689. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81690. this._indexBuffer = null;
  81691. }
  81692. while (this.lensFlares.length) {
  81693. this.lensFlares[0].dispose();
  81694. }
  81695. // Remove from scene
  81696. var index = this._scene.lensFlareSystems.indexOf(this);
  81697. this._scene.lensFlareSystems.splice(index, 1);
  81698. };
  81699. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81700. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81701. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81702. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81703. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81704. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81705. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81706. var parsedFlare = parsedLensFlareSystem.flares[index];
  81707. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81708. }
  81709. return lensFlareSystem;
  81710. };
  81711. LensFlareSystem.prototype.serialize = function () {
  81712. var serializationObject = {};
  81713. serializationObject.id = this.id;
  81714. serializationObject.name = this.name;
  81715. serializationObject.emitterId = this.getEmitter().id;
  81716. serializationObject.borderLimit = this.borderLimit;
  81717. serializationObject.flares = [];
  81718. for (var index = 0; index < this.lensFlares.length; index++) {
  81719. var flare = this.lensFlares[index];
  81720. serializationObject.flares.push({
  81721. size: flare.size,
  81722. position: flare.position,
  81723. color: flare.color.asArray(),
  81724. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81725. });
  81726. }
  81727. return serializationObject;
  81728. };
  81729. return LensFlareSystem;
  81730. }());
  81731. BABYLON.LensFlareSystem = LensFlareSystem;
  81732. })(BABYLON || (BABYLON = {}));
  81733. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81734. var BABYLON;
  81735. (function (BABYLON) {
  81736. /**
  81737. * This is a holder class for the physics joint created by the physics plugin.
  81738. * It holds a set of functions to control the underlying joint.
  81739. */
  81740. var PhysicsJoint = /** @class */ (function () {
  81741. function PhysicsJoint(type, jointData) {
  81742. this.type = type;
  81743. this.jointData = jointData;
  81744. jointData.nativeParams = jointData.nativeParams || {};
  81745. }
  81746. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81747. get: function () {
  81748. return this._physicsJoint;
  81749. },
  81750. set: function (newJoint) {
  81751. if (this._physicsJoint) {
  81752. //remove from the wolrd
  81753. }
  81754. this._physicsJoint = newJoint;
  81755. },
  81756. enumerable: true,
  81757. configurable: true
  81758. });
  81759. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81760. set: function (physicsPlugin) {
  81761. this._physicsPlugin = physicsPlugin;
  81762. },
  81763. enumerable: true,
  81764. configurable: true
  81765. });
  81766. /**
  81767. * Execute a function that is physics-plugin specific.
  81768. * @param {Function} func the function that will be executed.
  81769. * It accepts two parameters: the physics world and the physics joint.
  81770. */
  81771. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81772. func(this._physicsPlugin.world, this._physicsJoint);
  81773. };
  81774. //TODO check if the native joints are the same
  81775. //Joint Types
  81776. PhysicsJoint.DistanceJoint = 0;
  81777. PhysicsJoint.HingeJoint = 1;
  81778. PhysicsJoint.BallAndSocketJoint = 2;
  81779. PhysicsJoint.WheelJoint = 3;
  81780. PhysicsJoint.SliderJoint = 4;
  81781. //OIMO
  81782. PhysicsJoint.PrismaticJoint = 5;
  81783. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81784. PhysicsJoint.UniversalJoint = 6;
  81785. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81786. //Cannon
  81787. //Similar to a Ball-Joint. Different in params
  81788. PhysicsJoint.PointToPointJoint = 8;
  81789. //Cannon only at the moment
  81790. PhysicsJoint.SpringJoint = 9;
  81791. PhysicsJoint.LockJoint = 10;
  81792. return PhysicsJoint;
  81793. }());
  81794. BABYLON.PhysicsJoint = PhysicsJoint;
  81795. /**
  81796. * A class representing a physics distance joint.
  81797. */
  81798. var DistanceJoint = /** @class */ (function (_super) {
  81799. __extends(DistanceJoint, _super);
  81800. function DistanceJoint(jointData) {
  81801. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81802. }
  81803. /**
  81804. * Update the predefined distance.
  81805. */
  81806. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81807. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81808. };
  81809. return DistanceJoint;
  81810. }(PhysicsJoint));
  81811. BABYLON.DistanceJoint = DistanceJoint;
  81812. var MotorEnabledJoint = /** @class */ (function (_super) {
  81813. __extends(MotorEnabledJoint, _super);
  81814. function MotorEnabledJoint(type, jointData) {
  81815. return _super.call(this, type, jointData) || this;
  81816. }
  81817. /**
  81818. * Set the motor values.
  81819. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81820. * @param {number} force the force to apply
  81821. * @param {number} maxForce max force for this motor.
  81822. */
  81823. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81824. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81825. };
  81826. /**
  81827. * Set the motor's limits.
  81828. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81829. */
  81830. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81831. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81832. };
  81833. return MotorEnabledJoint;
  81834. }(PhysicsJoint));
  81835. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81836. /**
  81837. * This class represents a single hinge physics joint
  81838. */
  81839. var HingeJoint = /** @class */ (function (_super) {
  81840. __extends(HingeJoint, _super);
  81841. function HingeJoint(jointData) {
  81842. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81843. }
  81844. /**
  81845. * Set the motor values.
  81846. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81847. * @param {number} force the force to apply
  81848. * @param {number} maxForce max force for this motor.
  81849. */
  81850. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81851. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81852. };
  81853. /**
  81854. * Set the motor's limits.
  81855. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81856. */
  81857. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81858. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81859. };
  81860. return HingeJoint;
  81861. }(MotorEnabledJoint));
  81862. BABYLON.HingeJoint = HingeJoint;
  81863. /**
  81864. * This class represents a dual hinge physics joint (same as wheel joint)
  81865. */
  81866. var Hinge2Joint = /** @class */ (function (_super) {
  81867. __extends(Hinge2Joint, _super);
  81868. function Hinge2Joint(jointData) {
  81869. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81870. }
  81871. /**
  81872. * Set the motor values.
  81873. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81874. * @param {number} force the force to apply
  81875. * @param {number} maxForce max force for this motor.
  81876. * @param {motorIndex} the motor's index, 0 or 1.
  81877. */
  81878. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81879. if (motorIndex === void 0) { motorIndex = 0; }
  81880. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81881. };
  81882. /**
  81883. * Set the motor limits.
  81884. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81885. * @param {number} upperLimit the upper limit
  81886. * @param {number} lowerLimit lower limit
  81887. * @param {motorIndex} the motor's index, 0 or 1.
  81888. */
  81889. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81890. if (motorIndex === void 0) { motorIndex = 0; }
  81891. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81892. };
  81893. return Hinge2Joint;
  81894. }(MotorEnabledJoint));
  81895. BABYLON.Hinge2Joint = Hinge2Joint;
  81896. })(BABYLON || (BABYLON = {}));
  81897. //# sourceMappingURL=babylon.physicsJoint.js.map
  81898. var BABYLON;
  81899. (function (BABYLON) {
  81900. var PhysicsImpostor = /** @class */ (function () {
  81901. function PhysicsImpostor(object, type, _options, _scene) {
  81902. if (_options === void 0) { _options = { mass: 0 }; }
  81903. var _this = this;
  81904. this.object = object;
  81905. this.type = type;
  81906. this._options = _options;
  81907. this._scene = _scene;
  81908. this._bodyUpdateRequired = false;
  81909. this._onBeforePhysicsStepCallbacks = new Array();
  81910. this._onAfterPhysicsStepCallbacks = new Array();
  81911. this._onPhysicsCollideCallbacks = [];
  81912. this._deltaPosition = BABYLON.Vector3.Zero();
  81913. this._isDisposed = false;
  81914. //temp variables for parent rotation calculations
  81915. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81916. this._tmpQuat = new BABYLON.Quaternion();
  81917. this._tmpQuat2 = new BABYLON.Quaternion();
  81918. /**
  81919. * this function is executed by the physics engine.
  81920. */
  81921. this.beforeStep = function () {
  81922. if (!_this._physicsEngine) {
  81923. return;
  81924. }
  81925. _this.object.translate(_this._deltaPosition, -1);
  81926. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81927. _this.object.computeWorldMatrix(false);
  81928. if (_this.object.parent && _this.object.rotationQuaternion) {
  81929. _this.getParentsRotation();
  81930. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81931. }
  81932. else {
  81933. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81934. }
  81935. if (!_this._options.disableBidirectionalTransformation) {
  81936. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81937. }
  81938. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81939. func(_this);
  81940. });
  81941. };
  81942. /**
  81943. * this function is executed by the physics engine.
  81944. */
  81945. this.afterStep = function () {
  81946. if (!_this._physicsEngine) {
  81947. return;
  81948. }
  81949. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81950. func(_this);
  81951. });
  81952. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81953. // object has now its world rotation. needs to be converted to local.
  81954. if (_this.object.parent && _this.object.rotationQuaternion) {
  81955. _this.getParentsRotation();
  81956. _this._tmpQuat.conjugateInPlace();
  81957. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81958. }
  81959. // take the position set and make it the absolute position of this object.
  81960. _this.object.setAbsolutePosition(_this.object.position);
  81961. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81962. _this.object.translate(_this._deltaPosition, 1);
  81963. };
  81964. /**
  81965. * Legacy collision detection event support
  81966. */
  81967. this.onCollideEvent = null;
  81968. //event and body object due to cannon's event-based architecture.
  81969. this.onCollide = function (e) {
  81970. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81971. return;
  81972. }
  81973. if (!_this._physicsEngine) {
  81974. return;
  81975. }
  81976. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81977. if (otherImpostor) {
  81978. // Legacy collision detection event support
  81979. if (_this.onCollideEvent) {
  81980. _this.onCollideEvent(_this, otherImpostor);
  81981. }
  81982. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81983. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81984. }).forEach(function (obj) {
  81985. obj.callback(_this, otherImpostor);
  81986. });
  81987. }
  81988. };
  81989. //sanity check!
  81990. if (!this.object) {
  81991. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81992. return;
  81993. }
  81994. //legacy support for old syntax.
  81995. if (!this._scene && object.getScene) {
  81996. this._scene = object.getScene();
  81997. }
  81998. if (!this._scene) {
  81999. return;
  82000. }
  82001. this._physicsEngine = this._scene.getPhysicsEngine();
  82002. if (!this._physicsEngine) {
  82003. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82004. }
  82005. else {
  82006. //set the object's quaternion, if not set
  82007. if (!this.object.rotationQuaternion) {
  82008. if (this.object.rotation) {
  82009. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82010. }
  82011. else {
  82012. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82013. }
  82014. }
  82015. //default options params
  82016. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82017. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82018. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82019. this._joints = [];
  82020. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82021. if (!this.object.parent || this._options.ignoreParent) {
  82022. this._init();
  82023. }
  82024. else if (this.object.parent.physicsImpostor) {
  82025. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82026. }
  82027. }
  82028. }
  82029. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82030. get: function () {
  82031. return this._isDisposed;
  82032. },
  82033. enumerable: true,
  82034. configurable: true
  82035. });
  82036. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82037. get: function () {
  82038. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82039. },
  82040. set: function (value) {
  82041. this.setMass(value);
  82042. },
  82043. enumerable: true,
  82044. configurable: true
  82045. });
  82046. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82047. get: function () {
  82048. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82049. },
  82050. set: function (value) {
  82051. if (!this._physicsEngine) {
  82052. return;
  82053. }
  82054. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82055. },
  82056. enumerable: true,
  82057. configurable: true
  82058. });
  82059. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82060. get: function () {
  82061. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82062. },
  82063. set: function (value) {
  82064. if (!this._physicsEngine) {
  82065. return;
  82066. }
  82067. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82068. },
  82069. enumerable: true,
  82070. configurable: true
  82071. });
  82072. /**
  82073. * This function will completly initialize this impostor.
  82074. * It will create a new body - but only if this mesh has no parent.
  82075. * If it has, this impostor will not be used other than to define the impostor
  82076. * of the child mesh.
  82077. */
  82078. PhysicsImpostor.prototype._init = function () {
  82079. if (!this._physicsEngine) {
  82080. return;
  82081. }
  82082. this._physicsEngine.removeImpostor(this);
  82083. this.physicsBody = null;
  82084. this._parent = this._parent || this._getPhysicsParent();
  82085. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82086. this._physicsEngine.addImpostor(this);
  82087. }
  82088. };
  82089. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82090. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82091. var parentMesh = this.object.parent;
  82092. return parentMesh.physicsImpostor;
  82093. }
  82094. return null;
  82095. };
  82096. /**
  82097. * Should a new body be generated.
  82098. */
  82099. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82100. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82101. };
  82102. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82103. this.forceUpdate();
  82104. };
  82105. /**
  82106. * Force a regeneration of this or the parent's impostor's body.
  82107. * Use under cautious - This will remove all joints already implemented.
  82108. */
  82109. PhysicsImpostor.prototype.forceUpdate = function () {
  82110. this._init();
  82111. if (this.parent && !this._options.ignoreParent) {
  82112. this.parent.forceUpdate();
  82113. }
  82114. };
  82115. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82116. /*public get mesh(): AbstractMesh {
  82117. return this._mesh;
  82118. }*/
  82119. /**
  82120. * Gets the body that holds this impostor. Either its own, or its parent.
  82121. */
  82122. get: function () {
  82123. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82124. },
  82125. /**
  82126. * Set the physics body. Used mainly by the physics engine/plugin
  82127. */
  82128. set: function (physicsBody) {
  82129. if (this._physicsBody && this._physicsEngine) {
  82130. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82131. }
  82132. this._physicsBody = physicsBody;
  82133. this.resetUpdateFlags();
  82134. },
  82135. enumerable: true,
  82136. configurable: true
  82137. });
  82138. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82139. get: function () {
  82140. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82141. },
  82142. set: function (value) {
  82143. this._parent = value;
  82144. },
  82145. enumerable: true,
  82146. configurable: true
  82147. });
  82148. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82149. this._bodyUpdateRequired = false;
  82150. };
  82151. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82152. if (this.object.getBoundingInfo) {
  82153. var q = this.object.rotationQuaternion;
  82154. //reset rotation
  82155. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82156. //calculate the world matrix with no rotation
  82157. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82158. var boundingInfo = this.object.getBoundingInfo();
  82159. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82160. //bring back the rotation
  82161. this.object.rotationQuaternion = q;
  82162. //calculate the world matrix with the new rotation
  82163. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82164. return size;
  82165. }
  82166. else {
  82167. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82168. }
  82169. };
  82170. PhysicsImpostor.prototype.getObjectCenter = function () {
  82171. if (this.object.getBoundingInfo) {
  82172. var boundingInfo = this.object.getBoundingInfo();
  82173. return boundingInfo.boundingBox.centerWorld;
  82174. }
  82175. else {
  82176. return this.object.position;
  82177. }
  82178. };
  82179. /**
  82180. * Get a specific parametes from the options parameter.
  82181. */
  82182. PhysicsImpostor.prototype.getParam = function (paramName) {
  82183. return this._options[paramName];
  82184. };
  82185. /**
  82186. * Sets a specific parameter in the options given to the physics plugin
  82187. */
  82188. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82189. this._options[paramName] = value;
  82190. this._bodyUpdateRequired = true;
  82191. };
  82192. /**
  82193. * Specifically change the body's mass option. Won't recreate the physics body object
  82194. */
  82195. PhysicsImpostor.prototype.setMass = function (mass) {
  82196. if (this.getParam("mass") !== mass) {
  82197. this.setParam("mass", mass);
  82198. }
  82199. if (this._physicsEngine) {
  82200. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82201. }
  82202. };
  82203. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82204. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82205. };
  82206. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82207. if (this._physicsEngine) {
  82208. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82209. }
  82210. };
  82211. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82212. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82213. };
  82214. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82215. if (this._physicsEngine) {
  82216. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82217. }
  82218. };
  82219. /**
  82220. * Execute a function with the physics plugin native code.
  82221. * Provide a function the will have two variables - the world object and the physics body object.
  82222. */
  82223. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82224. if (this._physicsEngine) {
  82225. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82226. }
  82227. };
  82228. /**
  82229. * Register a function that will be executed before the physics world is stepping forward.
  82230. */
  82231. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82232. this._onBeforePhysicsStepCallbacks.push(func);
  82233. };
  82234. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82235. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82236. if (index > -1) {
  82237. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82238. }
  82239. else {
  82240. BABYLON.Tools.Warn("Function to remove was not found");
  82241. }
  82242. };
  82243. /**
  82244. * Register a function that will be executed after the physics step
  82245. */
  82246. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82247. this._onAfterPhysicsStepCallbacks.push(func);
  82248. };
  82249. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82250. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82251. if (index > -1) {
  82252. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82253. }
  82254. else {
  82255. BABYLON.Tools.Warn("Function to remove was not found");
  82256. }
  82257. };
  82258. /**
  82259. * register a function that will be executed when this impostor collides against a different body.
  82260. */
  82261. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82262. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82263. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82264. };
  82265. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82266. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82267. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82268. if (index > -1) {
  82269. this._onPhysicsCollideCallbacks.splice(index, 1);
  82270. }
  82271. else {
  82272. BABYLON.Tools.Warn("Function to remove was not found");
  82273. }
  82274. };
  82275. PhysicsImpostor.prototype.getParentsRotation = function () {
  82276. var parent = this.object.parent;
  82277. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82278. while (parent) {
  82279. if (parent.rotationQuaternion) {
  82280. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82281. }
  82282. else {
  82283. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82284. }
  82285. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82286. parent = parent.parent;
  82287. }
  82288. return this._tmpQuat;
  82289. };
  82290. /**
  82291. * Apply a force
  82292. */
  82293. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82294. if (this._physicsEngine) {
  82295. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82296. }
  82297. return this;
  82298. };
  82299. /**
  82300. * Apply an impulse
  82301. */
  82302. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82303. if (this._physicsEngine) {
  82304. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82305. }
  82306. return this;
  82307. };
  82308. /**
  82309. * A help function to create a joint.
  82310. */
  82311. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82312. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82313. this.addJoint(otherImpostor, joint);
  82314. return this;
  82315. };
  82316. /**
  82317. * Add a joint to this impostor with a different impostor.
  82318. */
  82319. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82320. this._joints.push({
  82321. otherImpostor: otherImpostor,
  82322. joint: joint
  82323. });
  82324. if (this._physicsEngine) {
  82325. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82326. }
  82327. return this;
  82328. };
  82329. /**
  82330. * Will keep this body still, in a sleep mode.
  82331. */
  82332. PhysicsImpostor.prototype.sleep = function () {
  82333. if (this._physicsEngine) {
  82334. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82335. }
  82336. return this;
  82337. };
  82338. /**
  82339. * Wake the body up.
  82340. */
  82341. PhysicsImpostor.prototype.wakeUp = function () {
  82342. if (this._physicsEngine) {
  82343. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82344. }
  82345. return this;
  82346. };
  82347. PhysicsImpostor.prototype.clone = function (newObject) {
  82348. if (!newObject)
  82349. return null;
  82350. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82351. };
  82352. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82353. var _this = this;
  82354. //no dispose if no physics engine is available.
  82355. if (!this._physicsEngine) {
  82356. return;
  82357. }
  82358. this._joints.forEach(function (j) {
  82359. if (_this._physicsEngine) {
  82360. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82361. }
  82362. });
  82363. //dispose the physics body
  82364. this._physicsEngine.removeImpostor(this);
  82365. if (this.parent) {
  82366. this.parent.forceUpdate();
  82367. }
  82368. else {
  82369. /*this._object.getChildMeshes().forEach(function(mesh) {
  82370. if (mesh.physicsImpostor) {
  82371. if (disposeChildren) {
  82372. mesh.physicsImpostor.dispose();
  82373. mesh.physicsImpostor = null;
  82374. }
  82375. }
  82376. })*/
  82377. }
  82378. this._isDisposed = true;
  82379. };
  82380. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82381. this._deltaPosition.copyFrom(position);
  82382. };
  82383. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82384. if (!this._deltaRotation) {
  82385. this._deltaRotation = new BABYLON.Quaternion();
  82386. }
  82387. this._deltaRotation.copyFrom(rotation);
  82388. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82389. };
  82390. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82391. if (this._physicsEngine) {
  82392. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82393. }
  82394. return this;
  82395. };
  82396. PhysicsImpostor.prototype.getRadius = function () {
  82397. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82398. };
  82399. /**
  82400. * Sync a bone with this impostor
  82401. * @param bone The bone to sync to the impostor.
  82402. * @param boneMesh The mesh that the bone is influencing.
  82403. * @param jointPivot The pivot of the joint / bone in local space.
  82404. * @param distToJoint Optional distance from the impostor to the joint.
  82405. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82406. */
  82407. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82408. var tempVec = PhysicsImpostor._tmpVecs[0];
  82409. var mesh = this.object;
  82410. if (mesh.rotationQuaternion) {
  82411. if (adjustRotation) {
  82412. var tempQuat = PhysicsImpostor._tmpQuat;
  82413. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82414. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82415. }
  82416. else {
  82417. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82418. }
  82419. }
  82420. tempVec.x = 0;
  82421. tempVec.y = 0;
  82422. tempVec.z = 0;
  82423. if (jointPivot) {
  82424. tempVec.x = jointPivot.x;
  82425. tempVec.y = jointPivot.y;
  82426. tempVec.z = jointPivot.z;
  82427. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82428. if (distToJoint === undefined || distToJoint === null) {
  82429. distToJoint = jointPivot.length();
  82430. }
  82431. tempVec.x *= distToJoint;
  82432. tempVec.y *= distToJoint;
  82433. tempVec.z *= distToJoint;
  82434. }
  82435. if (bone.getParent()) {
  82436. tempVec.addInPlace(mesh.getAbsolutePosition());
  82437. bone.setAbsolutePosition(tempVec, boneMesh);
  82438. }
  82439. else {
  82440. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82441. boneMesh.position.x -= tempVec.x;
  82442. boneMesh.position.y -= tempVec.y;
  82443. boneMesh.position.z -= tempVec.z;
  82444. }
  82445. };
  82446. /**
  82447. * Sync impostor to a bone
  82448. * @param bone The bone that the impostor will be synced to.
  82449. * @param boneMesh The mesh that the bone is influencing.
  82450. * @param jointPivot The pivot of the joint / bone in local space.
  82451. * @param distToJoint Optional distance from the impostor to the joint.
  82452. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82453. * @param boneAxis Optional vector3 axis the bone is aligned with
  82454. */
  82455. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82456. var mesh = this.object;
  82457. if (mesh.rotationQuaternion) {
  82458. if (adjustRotation) {
  82459. var tempQuat = PhysicsImpostor._tmpQuat;
  82460. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82461. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82462. }
  82463. else {
  82464. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82465. }
  82466. }
  82467. var pos = PhysicsImpostor._tmpVecs[0];
  82468. var boneDir = PhysicsImpostor._tmpVecs[1];
  82469. if (!boneAxis) {
  82470. boneAxis = PhysicsImpostor._tmpVecs[2];
  82471. boneAxis.x = 0;
  82472. boneAxis.y = 1;
  82473. boneAxis.z = 0;
  82474. }
  82475. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82476. bone.getAbsolutePositionToRef(boneMesh, pos);
  82477. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82478. distToJoint = jointPivot.length();
  82479. }
  82480. if (distToJoint !== undefined && distToJoint !== null) {
  82481. pos.x += boneDir.x * distToJoint;
  82482. pos.y += boneDir.y * distToJoint;
  82483. pos.z += boneDir.z * distToJoint;
  82484. }
  82485. mesh.setAbsolutePosition(pos);
  82486. };
  82487. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82488. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82489. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82490. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82491. //Impostor types
  82492. PhysicsImpostor.NoImpostor = 0;
  82493. PhysicsImpostor.SphereImpostor = 1;
  82494. PhysicsImpostor.BoxImpostor = 2;
  82495. PhysicsImpostor.PlaneImpostor = 3;
  82496. PhysicsImpostor.MeshImpostor = 4;
  82497. PhysicsImpostor.CylinderImpostor = 7;
  82498. PhysicsImpostor.ParticleImpostor = 8;
  82499. PhysicsImpostor.HeightmapImpostor = 9;
  82500. return PhysicsImpostor;
  82501. }());
  82502. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82503. })(BABYLON || (BABYLON = {}));
  82504. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82505. var BABYLON;
  82506. (function (BABYLON) {
  82507. var PhysicsEngine = /** @class */ (function () {
  82508. function PhysicsEngine(gravity, _physicsPlugin) {
  82509. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82510. this._physicsPlugin = _physicsPlugin;
  82511. //new methods and parameters
  82512. this._impostors = [];
  82513. this._joints = [];
  82514. if (!this._physicsPlugin.isSupported()) {
  82515. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82516. + "Please make sure it is included.");
  82517. }
  82518. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82519. this.setGravity(gravity);
  82520. this.setTimeStep();
  82521. }
  82522. PhysicsEngine.prototype.setGravity = function (gravity) {
  82523. this.gravity = gravity;
  82524. this._physicsPlugin.setGravity(this.gravity);
  82525. };
  82526. /**
  82527. * Set the time step of the physics engine.
  82528. * default is 1/60.
  82529. * To slow it down, enter 1/600 for example.
  82530. * To speed it up, 1/30
  82531. * @param {number} newTimeStep the new timestep to apply to this world.
  82532. */
  82533. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82534. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82535. this._physicsPlugin.setTimeStep(newTimeStep);
  82536. };
  82537. /**
  82538. * Get the time step of the physics engine.
  82539. */
  82540. PhysicsEngine.prototype.getTimeStep = function () {
  82541. return this._physicsPlugin.getTimeStep();
  82542. };
  82543. PhysicsEngine.prototype.dispose = function () {
  82544. this._impostors.forEach(function (impostor) {
  82545. impostor.dispose();
  82546. });
  82547. this._physicsPlugin.dispose();
  82548. };
  82549. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82550. return this._physicsPlugin.name;
  82551. };
  82552. /**
  82553. * Adding a new impostor for the impostor tracking.
  82554. * This will be done by the impostor itself.
  82555. * @param {PhysicsImpostor} impostor the impostor to add
  82556. */
  82557. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82558. impostor.uniqueId = this._impostors.push(impostor);
  82559. //if no parent, generate the body
  82560. if (!impostor.parent) {
  82561. this._physicsPlugin.generatePhysicsBody(impostor);
  82562. }
  82563. };
  82564. /**
  82565. * Remove an impostor from the engine.
  82566. * This impostor and its mesh will not longer be updated by the physics engine.
  82567. * @param {PhysicsImpostor} impostor the impostor to remove
  82568. */
  82569. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82570. var index = this._impostors.indexOf(impostor);
  82571. if (index > -1) {
  82572. var removed = this._impostors.splice(index, 1);
  82573. //Is it needed?
  82574. if (removed.length) {
  82575. //this will also remove it from the world.
  82576. removed[0].physicsBody = null;
  82577. }
  82578. }
  82579. };
  82580. /**
  82581. * Add a joint to the physics engine
  82582. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82583. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82584. * @param {PhysicsJoint} the joint that will connect both impostors.
  82585. */
  82586. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82587. var impostorJoint = {
  82588. mainImpostor: mainImpostor,
  82589. connectedImpostor: connectedImpostor,
  82590. joint: joint
  82591. };
  82592. joint.physicsPlugin = this._physicsPlugin;
  82593. this._joints.push(impostorJoint);
  82594. this._physicsPlugin.generateJoint(impostorJoint);
  82595. };
  82596. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82597. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82598. return (impostorJoint.connectedImpostor === connectedImpostor
  82599. && impostorJoint.joint === joint
  82600. && impostorJoint.mainImpostor === mainImpostor);
  82601. });
  82602. if (matchingJoints.length) {
  82603. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82604. //TODO remove it from the list as well
  82605. }
  82606. };
  82607. /**
  82608. * Called by the scene. no need to call it.
  82609. */
  82610. PhysicsEngine.prototype._step = function (delta) {
  82611. var _this = this;
  82612. //check if any mesh has no body / requires an update
  82613. this._impostors.forEach(function (impostor) {
  82614. if (impostor.isBodyInitRequired()) {
  82615. _this._physicsPlugin.generatePhysicsBody(impostor);
  82616. }
  82617. });
  82618. if (delta > 0.1) {
  82619. delta = 0.1;
  82620. }
  82621. else if (delta <= 0) {
  82622. delta = 1.0 / 60.0;
  82623. }
  82624. this._physicsPlugin.executeStep(delta, this._impostors);
  82625. };
  82626. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82627. return this._physicsPlugin;
  82628. };
  82629. PhysicsEngine.prototype.getImpostors = function () {
  82630. return this._impostors;
  82631. };
  82632. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82633. for (var i = 0; i < this._impostors.length; ++i) {
  82634. if (this._impostors[i].object === object) {
  82635. return this._impostors[i];
  82636. }
  82637. }
  82638. return null;
  82639. };
  82640. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82641. for (var i = 0; i < this._impostors.length; ++i) {
  82642. if (this._impostors[i].physicsBody === body) {
  82643. return this._impostors[i];
  82644. }
  82645. }
  82646. return null;
  82647. };
  82648. // Statics
  82649. PhysicsEngine.Epsilon = 0.001;
  82650. return PhysicsEngine;
  82651. }());
  82652. BABYLON.PhysicsEngine = PhysicsEngine;
  82653. })(BABYLON || (BABYLON = {}));
  82654. //# sourceMappingURL=babylon.physicsEngine.js.map
  82655. var BABYLON;
  82656. (function (BABYLON) {
  82657. var PhysicsHelper = /** @class */ (function () {
  82658. function PhysicsHelper(scene) {
  82659. this._scene = scene;
  82660. this._physicsEngine = this._scene.getPhysicsEngine();
  82661. if (!this._physicsEngine) {
  82662. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82663. }
  82664. }
  82665. /**
  82666. * @param {Vector3} origin the origin of the explosion
  82667. * @param {number} radius the explosion radius
  82668. * @param {number} strength the explosion strength
  82669. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82670. */
  82671. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82672. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82673. if (!this._physicsEngine) {
  82674. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82675. return null;
  82676. }
  82677. var impostors = this._physicsEngine.getImpostors();
  82678. if (impostors.length === 0) {
  82679. return null;
  82680. }
  82681. var event = new PhysicsRadialExplosionEvent(this._scene);
  82682. impostors.forEach(function (impostor) {
  82683. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82684. if (!impostorForceAndContactPoint) {
  82685. return;
  82686. }
  82687. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82688. });
  82689. event.dispose(false);
  82690. return event;
  82691. };
  82692. /**
  82693. * @param {Vector3} origin the origin of the explosion
  82694. * @param {number} radius the explosion radius
  82695. * @param {number} strength the explosion strength
  82696. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82697. */
  82698. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82699. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82700. if (!this._physicsEngine) {
  82701. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82702. return null;
  82703. }
  82704. var impostors = this._physicsEngine.getImpostors();
  82705. if (impostors.length === 0) {
  82706. return null;
  82707. }
  82708. var event = new PhysicsRadialExplosionEvent(this._scene);
  82709. impostors.forEach(function (impostor) {
  82710. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82711. if (!impostorForceAndContactPoint) {
  82712. return;
  82713. }
  82714. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82715. });
  82716. event.dispose(false);
  82717. return event;
  82718. };
  82719. /**
  82720. * @param {Vector3} origin the origin of the explosion
  82721. * @param {number} radius the explosion radius
  82722. * @param {number} strength the explosion strength
  82723. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82724. */
  82725. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82726. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82727. if (!this._physicsEngine) {
  82728. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82729. return null;
  82730. }
  82731. var impostors = this._physicsEngine.getImpostors();
  82732. if (impostors.length === 0) {
  82733. return null;
  82734. }
  82735. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82736. event.dispose(false);
  82737. return event;
  82738. };
  82739. /**
  82740. * @param {Vector3} origin the origin of the updraft
  82741. * @param {number} radius the radius of the updraft
  82742. * @param {number} strength the strength of the updraft
  82743. * @param {number} height the height of the updraft
  82744. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82745. */
  82746. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82747. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82748. if (!this._physicsEngine) {
  82749. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82750. return null;
  82751. }
  82752. if (this._physicsEngine.getImpostors().length === 0) {
  82753. return null;
  82754. }
  82755. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82756. event.dispose(false);
  82757. return event;
  82758. };
  82759. /**
  82760. * @param {Vector3} origin the of the vortex
  82761. * @param {number} radius the radius of the vortex
  82762. * @param {number} strength the strength of the vortex
  82763. * @param {number} height the height of the vortex
  82764. */
  82765. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82766. if (!this._physicsEngine) {
  82767. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82768. return null;
  82769. }
  82770. if (this._physicsEngine.getImpostors().length === 0) {
  82771. return null;
  82772. }
  82773. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82774. event.dispose(false);
  82775. return event;
  82776. };
  82777. return PhysicsHelper;
  82778. }());
  82779. BABYLON.PhysicsHelper = PhysicsHelper;
  82780. /***** Radial explosion *****/
  82781. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82782. function PhysicsRadialExplosionEvent(scene) {
  82783. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82784. this._rays = [];
  82785. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82786. this._scene = scene;
  82787. }
  82788. /**
  82789. * Returns the data related to the radial explosion event (sphere & rays).
  82790. * @returns {PhysicsRadialExplosionEventData}
  82791. */
  82792. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82793. this._dataFetched = true;
  82794. return {
  82795. sphere: this._sphere,
  82796. rays: this._rays,
  82797. };
  82798. };
  82799. /**
  82800. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82801. * @param impostor
  82802. * @param {Vector3} origin the origin of the explosion
  82803. * @param {number} radius the explosion radius
  82804. * @param {number} strength the explosion strength
  82805. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82806. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82807. */
  82808. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82809. if (impostor.mass === 0) {
  82810. return null;
  82811. }
  82812. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82813. return null;
  82814. }
  82815. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82816. return null;
  82817. }
  82818. var impostorObjectCenter = impostor.getObjectCenter();
  82819. var direction = impostorObjectCenter.subtract(origin);
  82820. var ray = new BABYLON.Ray(origin, direction, radius);
  82821. this._rays.push(ray);
  82822. var hit = ray.intersectsMesh(impostor.object);
  82823. var contactPoint = hit.pickedPoint;
  82824. if (!contactPoint) {
  82825. return null;
  82826. }
  82827. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82828. if (distanceFromOrigin > radius) {
  82829. return null;
  82830. }
  82831. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82832. ? strength
  82833. : strength * (1 - (distanceFromOrigin / radius));
  82834. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82835. return { force: force, contactPoint: contactPoint };
  82836. };
  82837. /**
  82838. * Disposes the sphere.
  82839. * @param {bolean} force
  82840. */
  82841. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82842. var _this = this;
  82843. if (force === void 0) { force = true; }
  82844. if (force) {
  82845. this._sphere.dispose();
  82846. }
  82847. else {
  82848. setTimeout(function () {
  82849. if (!_this._dataFetched) {
  82850. _this._sphere.dispose();
  82851. }
  82852. }, 0);
  82853. }
  82854. };
  82855. /*** Helpers ***/
  82856. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82857. if (!this._sphere) {
  82858. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82859. this._sphere.isVisible = false;
  82860. }
  82861. };
  82862. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82863. var impostorObject = impostor.object;
  82864. this._prepareSphere();
  82865. this._sphere.position = origin;
  82866. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82867. this._sphere._updateBoundingInfo();
  82868. this._sphere.computeWorldMatrix(true);
  82869. return this._sphere.intersectsMesh(impostorObject, true);
  82870. };
  82871. return PhysicsRadialExplosionEvent;
  82872. }());
  82873. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82874. /***** Gravitational Field *****/
  82875. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82876. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82877. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82878. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82879. this._physicsHelper = physicsHelper;
  82880. this._scene = scene;
  82881. this._origin = origin;
  82882. this._radius = radius;
  82883. this._strength = strength;
  82884. this._falloff = falloff;
  82885. this._tickCallback = this._tick.bind(this);
  82886. }
  82887. /**
  82888. * Returns the data related to the gravitational field event (sphere).
  82889. * @returns {PhysicsGravitationalFieldEventData}
  82890. */
  82891. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82892. this._dataFetched = true;
  82893. return {
  82894. sphere: this._sphere,
  82895. };
  82896. };
  82897. /**
  82898. * Enables the gravitational field.
  82899. */
  82900. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82901. this._tickCallback.call(this);
  82902. this._scene.registerBeforeRender(this._tickCallback);
  82903. };
  82904. /**
  82905. * Disables the gravitational field.
  82906. */
  82907. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82908. this._scene.unregisterBeforeRender(this._tickCallback);
  82909. };
  82910. /**
  82911. * Disposes the sphere.
  82912. * @param {bolean} force
  82913. */
  82914. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82915. var _this = this;
  82916. if (force === void 0) { force = true; }
  82917. if (force) {
  82918. this._sphere.dispose();
  82919. }
  82920. else {
  82921. setTimeout(function () {
  82922. if (!_this._dataFetched) {
  82923. _this._sphere.dispose();
  82924. }
  82925. }, 0);
  82926. }
  82927. };
  82928. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82929. // Since the params won't change, we fetch the event only once
  82930. if (this._sphere) {
  82931. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82932. }
  82933. else {
  82934. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82935. if (radialExplosionEvent) {
  82936. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82937. }
  82938. }
  82939. };
  82940. return PhysicsGravitationalFieldEvent;
  82941. }());
  82942. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82943. /***** Updraft *****/
  82944. var PhysicsUpdraftEvent = /** @class */ (function () {
  82945. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82946. this._scene = _scene;
  82947. this._origin = _origin;
  82948. this._radius = _radius;
  82949. this._strength = _strength;
  82950. this._height = _height;
  82951. this._updraftMode = _updraftMode;
  82952. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82953. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82954. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82955. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82956. this._physicsEngine = this._scene.getPhysicsEngine();
  82957. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82958. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82959. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82960. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82961. }
  82962. this._tickCallback = this._tick.bind(this);
  82963. }
  82964. /**
  82965. * Returns the data related to the updraft event (cylinder).
  82966. * @returns {PhysicsUpdraftEventData}
  82967. */
  82968. PhysicsUpdraftEvent.prototype.getData = function () {
  82969. this._dataFetched = true;
  82970. return {
  82971. cylinder: this._cylinder,
  82972. };
  82973. };
  82974. /**
  82975. * Enables the updraft.
  82976. */
  82977. PhysicsUpdraftEvent.prototype.enable = function () {
  82978. this._tickCallback.call(this);
  82979. this._scene.registerBeforeRender(this._tickCallback);
  82980. };
  82981. /**
  82982. * Disables the cortex.
  82983. */
  82984. PhysicsUpdraftEvent.prototype.disable = function () {
  82985. this._scene.unregisterBeforeRender(this._tickCallback);
  82986. };
  82987. /**
  82988. * Disposes the sphere.
  82989. * @param {bolean} force
  82990. */
  82991. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82992. var _this = this;
  82993. if (force === void 0) { force = true; }
  82994. if (force) {
  82995. this._cylinder.dispose();
  82996. }
  82997. else {
  82998. setTimeout(function () {
  82999. if (!_this._dataFetched) {
  83000. _this._cylinder.dispose();
  83001. }
  83002. }, 0);
  83003. }
  83004. };
  83005. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83006. if (impostor.mass === 0) {
  83007. return null;
  83008. }
  83009. if (!this._intersectsWithCylinder(impostor)) {
  83010. return null;
  83011. }
  83012. var impostorObjectCenter = impostor.getObjectCenter();
  83013. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83014. var direction = this._originDirection;
  83015. }
  83016. else {
  83017. var direction = impostorObjectCenter.subtract(this._originTop);
  83018. }
  83019. var multiplier = this._strength * -1;
  83020. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83021. return { force: force, contactPoint: impostorObjectCenter };
  83022. };
  83023. PhysicsUpdraftEvent.prototype._tick = function () {
  83024. var _this = this;
  83025. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83026. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83027. if (!impostorForceAndContactPoint) {
  83028. return;
  83029. }
  83030. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83031. });
  83032. };
  83033. /*** Helpers ***/
  83034. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83035. if (!this._cylinder) {
  83036. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83037. height: this._height,
  83038. diameter: this._radius * 2,
  83039. }, this._scene);
  83040. this._cylinder.isVisible = false;
  83041. }
  83042. };
  83043. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83044. var impostorObject = impostor.object;
  83045. this._prepareCylinder();
  83046. this._cylinder.position = this._cylinderPosition;
  83047. return this._cylinder.intersectsMesh(impostorObject, true);
  83048. };
  83049. return PhysicsUpdraftEvent;
  83050. }());
  83051. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83052. /***** Vortex *****/
  83053. var PhysicsVortexEvent = /** @class */ (function () {
  83054. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83055. this._scene = _scene;
  83056. this._origin = _origin;
  83057. this._radius = _radius;
  83058. this._strength = _strength;
  83059. this._height = _height;
  83060. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83061. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83062. this._updraftMultiplier = 0.02;
  83063. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83064. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83065. this._physicsEngine = this._scene.getPhysicsEngine();
  83066. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83067. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83068. this._tickCallback = this._tick.bind(this);
  83069. }
  83070. /**
  83071. * Returns the data related to the vortex event (cylinder).
  83072. * @returns {PhysicsVortexEventData}
  83073. */
  83074. PhysicsVortexEvent.prototype.getData = function () {
  83075. this._dataFetched = true;
  83076. return {
  83077. cylinder: this._cylinder,
  83078. };
  83079. };
  83080. /**
  83081. * Enables the vortex.
  83082. */
  83083. PhysicsVortexEvent.prototype.enable = function () {
  83084. this._tickCallback.call(this);
  83085. this._scene.registerBeforeRender(this._tickCallback);
  83086. };
  83087. /**
  83088. * Disables the cortex.
  83089. */
  83090. PhysicsVortexEvent.prototype.disable = function () {
  83091. this._scene.unregisterBeforeRender(this._tickCallback);
  83092. };
  83093. /**
  83094. * Disposes the sphere.
  83095. * @param {bolean} force
  83096. */
  83097. PhysicsVortexEvent.prototype.dispose = function (force) {
  83098. var _this = this;
  83099. if (force === void 0) { force = true; }
  83100. if (force) {
  83101. this._cylinder.dispose();
  83102. }
  83103. else {
  83104. setTimeout(function () {
  83105. if (!_this._dataFetched) {
  83106. _this._cylinder.dispose();
  83107. }
  83108. }, 0);
  83109. }
  83110. };
  83111. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83112. if (impostor.mass === 0) {
  83113. return null;
  83114. }
  83115. if (!this._intersectsWithCylinder(impostor)) {
  83116. return null;
  83117. }
  83118. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83119. return null;
  83120. }
  83121. var impostorObjectCenter = impostor.getObjectCenter();
  83122. 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)
  83123. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83124. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83125. var hit = ray.intersectsMesh(impostor.object);
  83126. var contactPoint = hit.pickedPoint;
  83127. if (!contactPoint) {
  83128. return null;
  83129. }
  83130. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83131. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83132. var directionToOrigin = contactPoint.normalize();
  83133. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83134. directionToOrigin = directionToOrigin.negate();
  83135. }
  83136. // TODO: find a more physically based solution
  83137. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83138. var forceX = directionToOrigin.x * this._strength / 8;
  83139. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83140. var forceZ = directionToOrigin.z * this._strength / 8;
  83141. }
  83142. else {
  83143. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83144. var forceY = this._originTop.y * this._updraftMultiplier;
  83145. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83146. }
  83147. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83148. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83149. return { force: force, contactPoint: impostorObjectCenter };
  83150. };
  83151. PhysicsVortexEvent.prototype._tick = function () {
  83152. var _this = this;
  83153. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83154. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83155. if (!impostorForceAndContactPoint) {
  83156. return;
  83157. }
  83158. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83159. });
  83160. };
  83161. /*** Helpers ***/
  83162. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83163. if (!this._cylinder) {
  83164. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83165. height: this._height,
  83166. diameter: this._radius * 2,
  83167. }, this._scene);
  83168. this._cylinder.isVisible = false;
  83169. }
  83170. };
  83171. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83172. var impostorObject = impostor.object;
  83173. this._prepareCylinder();
  83174. this._cylinder.position = this._cylinderPosition;
  83175. return this._cylinder.intersectsMesh(impostorObject, true);
  83176. };
  83177. return PhysicsVortexEvent;
  83178. }());
  83179. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83180. /***** Enums *****/
  83181. /**
  83182. * The strenght of the force in correspondence to the distance of the affected object
  83183. */
  83184. var PhysicsRadialImpulseFalloff;
  83185. (function (PhysicsRadialImpulseFalloff) {
  83186. /** Defines that impulse is constant in strength across it's whole radius */
  83187. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83188. /** DEfines that impulse gets weaker if it's further from the origin */
  83189. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83190. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83191. /**
  83192. * The strenght of the force in correspondence to the distance of the affected object
  83193. */
  83194. var PhysicsUpdraftMode;
  83195. (function (PhysicsUpdraftMode) {
  83196. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83197. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83198. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83199. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83200. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83201. })(BABYLON || (BABYLON = {}));
  83202. //# sourceMappingURL=babylon.physicsHelper.js.map
  83203. var BABYLON;
  83204. (function (BABYLON) {
  83205. var CannonJSPlugin = /** @class */ (function () {
  83206. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83207. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83208. if (iterations === void 0) { iterations = 10; }
  83209. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83210. this.name = "CannonJSPlugin";
  83211. this._physicsMaterials = new Array();
  83212. this._fixedTimeStep = 1 / 60;
  83213. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83214. this.BJSCANNON = CANNON;
  83215. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83216. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83217. this._tmpPosition = BABYLON.Vector3.Zero();
  83218. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83219. this._tmpUnityRotation = new BABYLON.Quaternion();
  83220. if (!this.isSupported()) {
  83221. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83222. return;
  83223. }
  83224. this._extendNamespace();
  83225. this.world = new this.BJSCANNON.World();
  83226. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83227. this.world.solver.iterations = iterations;
  83228. }
  83229. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83230. this.world.gravity.copy(gravity);
  83231. };
  83232. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83233. this._fixedTimeStep = timeStep;
  83234. };
  83235. CannonJSPlugin.prototype.getTimeStep = function () {
  83236. return this._fixedTimeStep;
  83237. };
  83238. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83239. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83240. };
  83241. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83242. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83243. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83244. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83245. };
  83246. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83247. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83248. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83249. impostor.physicsBody.applyForce(impulse, worldPoint);
  83250. };
  83251. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83252. //parent-child relationship. Does this impostor has a parent impostor?
  83253. if (impostor.parent) {
  83254. if (impostor.physicsBody) {
  83255. this.removePhysicsBody(impostor);
  83256. //TODO is that needed?
  83257. impostor.forceUpdate();
  83258. }
  83259. return;
  83260. }
  83261. //should a new body be created for this impostor?
  83262. if (impostor.isBodyInitRequired()) {
  83263. var shape = this._createShape(impostor);
  83264. //unregister events, if body is being changed
  83265. var oldBody = impostor.physicsBody;
  83266. if (oldBody) {
  83267. this.removePhysicsBody(impostor);
  83268. }
  83269. //create the body and material
  83270. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83271. var bodyCreationObject = {
  83272. mass: impostor.getParam("mass"),
  83273. material: material
  83274. };
  83275. // A simple extend, in case native options were used.
  83276. var nativeOptions = impostor.getParam("nativeOptions");
  83277. for (var key in nativeOptions) {
  83278. if (nativeOptions.hasOwnProperty(key)) {
  83279. bodyCreationObject[key] = nativeOptions[key];
  83280. }
  83281. }
  83282. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83283. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83284. this.world.addEventListener("preStep", impostor.beforeStep);
  83285. this.world.addEventListener("postStep", impostor.afterStep);
  83286. impostor.physicsBody.addShape(shape);
  83287. this.world.add(impostor.physicsBody);
  83288. //try to keep the body moving in the right direction by taking old properties.
  83289. //Should be tested!
  83290. if (oldBody) {
  83291. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83292. impostor.physicsBody[param].copy(oldBody[param]);
  83293. });
  83294. }
  83295. this._processChildMeshes(impostor);
  83296. }
  83297. //now update the body's transformation
  83298. this._updatePhysicsBodyTransformation(impostor);
  83299. };
  83300. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83301. var _this = this;
  83302. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83303. var currentRotation = mainImpostor.object.rotationQuaternion;
  83304. if (meshChildren.length) {
  83305. var processMesh = function (localPosition, mesh) {
  83306. if (!currentRotation || !mesh.rotationQuaternion) {
  83307. return;
  83308. }
  83309. var childImpostor = mesh.getPhysicsImpostor();
  83310. if (childImpostor) {
  83311. var parent = childImpostor.parent;
  83312. if (parent !== mainImpostor) {
  83313. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83314. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83315. if (childImpostor.physicsBody) {
  83316. _this.removePhysicsBody(childImpostor);
  83317. childImpostor.physicsBody = null;
  83318. }
  83319. childImpostor.parent = mainImpostor;
  83320. childImpostor.resetUpdateFlags();
  83321. 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));
  83322. //Add the mass of the children.
  83323. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83324. }
  83325. }
  83326. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83327. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83328. };
  83329. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83330. }
  83331. };
  83332. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83333. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83334. this.world.removeEventListener("preStep", impostor.beforeStep);
  83335. this.world.removeEventListener("postStep", impostor.afterStep);
  83336. this.world.remove(impostor.physicsBody);
  83337. };
  83338. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83339. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83340. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83341. if (!mainBody || !connectedBody) {
  83342. return;
  83343. }
  83344. var constraint;
  83345. var jointData = impostorJoint.joint.jointData;
  83346. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83347. var constraintData = {
  83348. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83349. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83350. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83351. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83352. maxForce: jointData.nativeParams.maxForce,
  83353. collideConnected: !!jointData.collision
  83354. };
  83355. switch (impostorJoint.joint.type) {
  83356. case BABYLON.PhysicsJoint.HingeJoint:
  83357. case BABYLON.PhysicsJoint.Hinge2Joint:
  83358. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83359. break;
  83360. case BABYLON.PhysicsJoint.DistanceJoint:
  83361. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83362. break;
  83363. case BABYLON.PhysicsJoint.SpringJoint:
  83364. var springData = jointData;
  83365. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83366. restLength: springData.length,
  83367. stiffness: springData.stiffness,
  83368. damping: springData.damping,
  83369. localAnchorA: constraintData.pivotA,
  83370. localAnchorB: constraintData.pivotB
  83371. });
  83372. break;
  83373. case BABYLON.PhysicsJoint.LockJoint:
  83374. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83375. break;
  83376. case BABYLON.PhysicsJoint.PointToPointJoint:
  83377. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83378. default:
  83379. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83380. break;
  83381. }
  83382. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83383. constraint.collideConnected = !!jointData.collision;
  83384. impostorJoint.joint.physicsJoint = constraint;
  83385. //don't add spring as constraint, as it is not one.
  83386. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83387. this.world.addConstraint(constraint);
  83388. }
  83389. else {
  83390. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83391. constraint.applyForce();
  83392. });
  83393. }
  83394. };
  83395. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83396. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83397. };
  83398. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83399. var index;
  83400. var mat;
  83401. for (index = 0; index < this._physicsMaterials.length; index++) {
  83402. mat = this._physicsMaterials[index];
  83403. if (mat.friction === friction && mat.restitution === restitution) {
  83404. return mat;
  83405. }
  83406. }
  83407. var currentMat = new this.BJSCANNON.Material(name);
  83408. currentMat.friction = friction;
  83409. currentMat.restitution = restitution;
  83410. this._physicsMaterials.push(currentMat);
  83411. return currentMat;
  83412. };
  83413. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83414. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83415. };
  83416. CannonJSPlugin.prototype._createShape = function (impostor) {
  83417. var object = impostor.object;
  83418. var returnValue;
  83419. var extendSize = impostor.getObjectExtendSize();
  83420. switch (impostor.type) {
  83421. case BABYLON.PhysicsImpostor.SphereImpostor:
  83422. var radiusX = extendSize.x;
  83423. var radiusY = extendSize.y;
  83424. var radiusZ = extendSize.z;
  83425. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83426. break;
  83427. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83428. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83429. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83430. break;
  83431. case BABYLON.PhysicsImpostor.BoxImpostor:
  83432. var box = extendSize.scale(0.5);
  83433. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83434. break;
  83435. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83436. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83437. returnValue = new this.BJSCANNON.Plane();
  83438. break;
  83439. case BABYLON.PhysicsImpostor.MeshImpostor:
  83440. // should transform the vertex data to world coordinates!!
  83441. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83442. var rawFaces = object.getIndices ? object.getIndices() : [];
  83443. if (!rawVerts)
  83444. return;
  83445. // get only scale! so the object could transform correctly.
  83446. var oldPosition = object.position.clone();
  83447. var oldRotation = object.rotation && object.rotation.clone();
  83448. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83449. object.position.copyFromFloats(0, 0, 0);
  83450. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83451. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83452. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83453. var transform = object.computeWorldMatrix(true);
  83454. // convert rawVerts to object space
  83455. var temp = new Array();
  83456. var index;
  83457. for (index = 0; index < rawVerts.length; index += 3) {
  83458. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83459. }
  83460. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83461. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83462. //now set back the transformation!
  83463. object.position.copyFrom(oldPosition);
  83464. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83465. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83466. break;
  83467. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83468. var oldPosition2 = object.position.clone();
  83469. var oldRotation2 = object.rotation && object.rotation.clone();
  83470. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83471. object.position.copyFromFloats(0, 0, 0);
  83472. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83473. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83474. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83475. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83476. returnValue = this._createHeightmap(object);
  83477. object.position.copyFrom(oldPosition2);
  83478. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83479. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83480. object.computeWorldMatrix(true);
  83481. break;
  83482. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83483. returnValue = new this.BJSCANNON.Particle();
  83484. break;
  83485. }
  83486. return returnValue;
  83487. };
  83488. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83489. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83490. var transform = object.computeWorldMatrix(true);
  83491. // convert rawVerts to object space
  83492. var temp = new Array();
  83493. var index;
  83494. for (index = 0; index < pos.length; index += 3) {
  83495. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83496. }
  83497. pos = temp;
  83498. var matrix = new Array();
  83499. //For now pointDepth will not be used and will be automatically calculated.
  83500. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83501. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83502. var boundingInfo = object.getBoundingInfo();
  83503. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83504. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83505. var elementSize = dim * 2 / arraySize;
  83506. for (var i = 0; i < pos.length; i = i + 3) {
  83507. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83508. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83509. var y = -pos[i + 2] + minY;
  83510. if (!matrix[x]) {
  83511. matrix[x] = [];
  83512. }
  83513. if (!matrix[x][z]) {
  83514. matrix[x][z] = y;
  83515. }
  83516. matrix[x][z] = Math.max(y, matrix[x][z]);
  83517. }
  83518. for (var x = 0; x <= arraySize; ++x) {
  83519. if (!matrix[x]) {
  83520. var loc = 1;
  83521. while (!matrix[(x + loc) % arraySize]) {
  83522. loc++;
  83523. }
  83524. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83525. //console.log("missing x", x);
  83526. }
  83527. for (var z = 0; z <= arraySize; ++z) {
  83528. if (!matrix[x][z]) {
  83529. var loc = 1;
  83530. var newValue;
  83531. while (newValue === undefined) {
  83532. newValue = matrix[x][(z + loc++) % arraySize];
  83533. }
  83534. matrix[x][z] = newValue;
  83535. }
  83536. }
  83537. }
  83538. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83539. elementSize: elementSize
  83540. });
  83541. //For future reference, needed for body transformation
  83542. shape.minY = minY;
  83543. return shape;
  83544. };
  83545. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83546. var object = impostor.object;
  83547. //make sure it is updated...
  83548. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83549. // The delta between the mesh position and the mesh bounding box center
  83550. var bInfo = object.getBoundingInfo();
  83551. if (!bInfo)
  83552. return;
  83553. var center = impostor.getObjectCenter();
  83554. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83555. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83556. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83557. this._tmpPosition.copyFrom(center);
  83558. var quaternion = object.rotationQuaternion;
  83559. if (!quaternion) {
  83560. return;
  83561. }
  83562. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83563. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83564. //-90 DEG in X, precalculated
  83565. quaternion = quaternion.multiply(this._minus90X);
  83566. //Invert! (Precalculated, 90 deg in X)
  83567. //No need to clone. this will never change.
  83568. impostor.setDeltaRotation(this._plus90X);
  83569. }
  83570. //If it is a heightfield, if should be centered.
  83571. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83572. var mesh = object;
  83573. var boundingInfo = mesh.getBoundingInfo();
  83574. //calculate the correct body position:
  83575. var rotationQuaternion = mesh.rotationQuaternion;
  83576. mesh.rotationQuaternion = this._tmpUnityRotation;
  83577. mesh.computeWorldMatrix(true);
  83578. //get original center with no rotation
  83579. var c = center.clone();
  83580. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83581. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83582. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83583. mesh.setPreTransformMatrix(p);
  83584. mesh.computeWorldMatrix(true);
  83585. //calculate the translation
  83586. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83587. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83588. //add it inverted to the delta
  83589. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83590. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83591. //rotation is back
  83592. mesh.rotationQuaternion = rotationQuaternion;
  83593. mesh.setPreTransformMatrix(oldPivot);
  83594. mesh.computeWorldMatrix(true);
  83595. }
  83596. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83597. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83598. //this._tmpPosition.copyFrom(object.position);
  83599. }
  83600. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83601. //Now update the impostor object
  83602. impostor.physicsBody.position.copy(this._tmpPosition);
  83603. impostor.physicsBody.quaternion.copy(quaternion);
  83604. };
  83605. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83606. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83607. if (impostor.object.rotationQuaternion) {
  83608. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83609. }
  83610. };
  83611. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83612. impostor.physicsBody.position.copy(newPosition);
  83613. impostor.physicsBody.quaternion.copy(newRotation);
  83614. };
  83615. CannonJSPlugin.prototype.isSupported = function () {
  83616. return this.BJSCANNON !== undefined;
  83617. };
  83618. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83619. impostor.physicsBody.velocity.copy(velocity);
  83620. };
  83621. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83622. impostor.physicsBody.angularVelocity.copy(velocity);
  83623. };
  83624. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83625. var v = impostor.physicsBody.velocity;
  83626. if (!v) {
  83627. return null;
  83628. }
  83629. return new BABYLON.Vector3(v.x, v.y, v.z);
  83630. };
  83631. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83632. var v = impostor.physicsBody.angularVelocity;
  83633. if (!v) {
  83634. return null;
  83635. }
  83636. return new BABYLON.Vector3(v.x, v.y, v.z);
  83637. };
  83638. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83639. impostor.physicsBody.mass = mass;
  83640. impostor.physicsBody.updateMassProperties();
  83641. };
  83642. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83643. return impostor.physicsBody.mass;
  83644. };
  83645. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83646. return impostor.physicsBody.material.friction;
  83647. };
  83648. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83649. impostor.physicsBody.material.friction = friction;
  83650. };
  83651. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83652. return impostor.physicsBody.material.restitution;
  83653. };
  83654. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83655. impostor.physicsBody.material.restitution = restitution;
  83656. };
  83657. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83658. impostor.physicsBody.sleep();
  83659. };
  83660. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83661. impostor.physicsBody.wakeUp();
  83662. };
  83663. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83664. joint.physicsJoint.distance = maxDistance;
  83665. };
  83666. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83667. // if (!motorIndex) {
  83668. // joint.physicsJoint.enableMotor();
  83669. // }
  83670. // }
  83671. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83672. // if (!motorIndex) {
  83673. // joint.physicsJoint.disableMotor();
  83674. // }
  83675. // }
  83676. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83677. if (!motorIndex) {
  83678. joint.physicsJoint.enableMotor();
  83679. joint.physicsJoint.setMotorSpeed(speed);
  83680. if (maxForce) {
  83681. this.setLimit(joint, maxForce);
  83682. }
  83683. }
  83684. };
  83685. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83686. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83687. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83688. };
  83689. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83690. var body = impostor.physicsBody;
  83691. mesh.position.x = body.position.x;
  83692. mesh.position.y = body.position.y;
  83693. mesh.position.z = body.position.z;
  83694. if (mesh.rotationQuaternion) {
  83695. mesh.rotationQuaternion.x = body.quaternion.x;
  83696. mesh.rotationQuaternion.y = body.quaternion.y;
  83697. mesh.rotationQuaternion.z = body.quaternion.z;
  83698. mesh.rotationQuaternion.w = body.quaternion.w;
  83699. }
  83700. };
  83701. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83702. var shape = impostor.physicsBody.shapes[0];
  83703. return shape.boundingSphereRadius;
  83704. };
  83705. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83706. var shape = impostor.physicsBody.shapes[0];
  83707. result.x = shape.halfExtents.x * 2;
  83708. result.y = shape.halfExtents.y * 2;
  83709. result.z = shape.halfExtents.z * 2;
  83710. };
  83711. CannonJSPlugin.prototype.dispose = function () {
  83712. };
  83713. CannonJSPlugin.prototype._extendNamespace = function () {
  83714. //this will force cannon to execute at least one step when using interpolation
  83715. var step_tmp1 = new this.BJSCANNON.Vec3();
  83716. var Engine = this.BJSCANNON;
  83717. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83718. maxSubSteps = maxSubSteps || 10;
  83719. timeSinceLastCalled = timeSinceLastCalled || 0;
  83720. if (timeSinceLastCalled === 0) {
  83721. this.internalStep(dt);
  83722. this.time += dt;
  83723. }
  83724. else {
  83725. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83726. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83727. var t0 = performance.now();
  83728. for (var i = 0; i !== internalSteps; i++) {
  83729. this.internalStep(dt);
  83730. if (performance.now() - t0 > dt * 1000) {
  83731. break;
  83732. }
  83733. }
  83734. this.time += timeSinceLastCalled;
  83735. var h = this.time % dt;
  83736. var h_div_dt = h / dt;
  83737. var interpvelo = step_tmp1;
  83738. var bodies = this.bodies;
  83739. for (var j = 0; j !== bodies.length; j++) {
  83740. var b = bodies[j];
  83741. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83742. b.position.vsub(b.previousPosition, interpvelo);
  83743. interpvelo.scale(h_div_dt, interpvelo);
  83744. b.position.vadd(interpvelo, b.interpolatedPosition);
  83745. }
  83746. else {
  83747. b.interpolatedPosition.copy(b.position);
  83748. b.interpolatedQuaternion.copy(b.quaternion);
  83749. }
  83750. }
  83751. }
  83752. };
  83753. };
  83754. return CannonJSPlugin;
  83755. }());
  83756. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83757. })(BABYLON || (BABYLON = {}));
  83758. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83759. var BABYLON;
  83760. (function (BABYLON) {
  83761. var OimoJSPlugin = /** @class */ (function () {
  83762. function OimoJSPlugin(iterations) {
  83763. this.name = "OimoJSPlugin";
  83764. this._tmpImpostorsArray = [];
  83765. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83766. this.BJSOIMO = OIMO;
  83767. this.world = new this.BJSOIMO.World({
  83768. iterations: iterations
  83769. });
  83770. this.world.clear();
  83771. }
  83772. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83773. this.world.gravity.copy(gravity);
  83774. };
  83775. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83776. this.world.timeStep = timeStep;
  83777. };
  83778. OimoJSPlugin.prototype.getTimeStep = function () {
  83779. return this.world.timeStep;
  83780. };
  83781. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83782. var _this = this;
  83783. impostors.forEach(function (impostor) {
  83784. impostor.beforeStep();
  83785. });
  83786. this.world.step();
  83787. impostors.forEach(function (impostor) {
  83788. impostor.afterStep();
  83789. //update the ordered impostors array
  83790. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83791. });
  83792. //check for collisions
  83793. var contact = this.world.contacts;
  83794. while (contact !== null) {
  83795. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83796. contact = contact.next;
  83797. continue;
  83798. }
  83799. //is this body colliding with any other? get the impostor
  83800. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83801. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83802. if (!mainImpostor || !collidingImpostor) {
  83803. contact = contact.next;
  83804. continue;
  83805. }
  83806. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83807. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83808. contact = contact.next;
  83809. }
  83810. };
  83811. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83812. var mass = impostor.physicsBody.mass;
  83813. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83814. };
  83815. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83816. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83817. this.applyImpulse(impostor, force, contactPoint);
  83818. };
  83819. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83820. var _this = this;
  83821. //parent-child relationship. Does this impostor has a parent impostor?
  83822. if (impostor.parent) {
  83823. if (impostor.physicsBody) {
  83824. this.removePhysicsBody(impostor);
  83825. //TODO is that needed?
  83826. impostor.forceUpdate();
  83827. }
  83828. return;
  83829. }
  83830. if (impostor.isBodyInitRequired()) {
  83831. var bodyConfig = {
  83832. name: impostor.uniqueId,
  83833. //Oimo must have mass, also for static objects.
  83834. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83835. size: [],
  83836. type: [],
  83837. pos: [],
  83838. posShape: [],
  83839. rot: [],
  83840. rotShape: [],
  83841. move: impostor.getParam("mass") !== 0,
  83842. density: impostor.getParam("mass"),
  83843. friction: impostor.getParam("friction"),
  83844. restitution: impostor.getParam("restitution"),
  83845. //Supporting older versions of Oimo
  83846. world: this.world
  83847. };
  83848. var impostors = [impostor];
  83849. var addToArray = function (parent) {
  83850. if (!parent.getChildMeshes)
  83851. return;
  83852. parent.getChildMeshes().forEach(function (m) {
  83853. if (m.physicsImpostor) {
  83854. impostors.push(m.physicsImpostor);
  83855. //m.physicsImpostor._init();
  83856. }
  83857. });
  83858. };
  83859. addToArray(impostor.object);
  83860. var checkWithEpsilon_1 = function (value) {
  83861. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83862. };
  83863. impostors.forEach(function (i) {
  83864. if (!i.object.rotationQuaternion) {
  83865. return;
  83866. }
  83867. //get the correct bounding box
  83868. var oldQuaternion = i.object.rotationQuaternion;
  83869. var rot = oldQuaternion.toEulerAngles();
  83870. var extendSize = i.getObjectExtendSize();
  83871. var radToDeg = 57.295779513082320876;
  83872. if (i === impostor) {
  83873. var center = impostor.getObjectCenter();
  83874. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83875. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83876. //Can also use Array.prototype.push.apply
  83877. bodyConfig.pos.push(center.x);
  83878. bodyConfig.pos.push(center.y);
  83879. bodyConfig.pos.push(center.z);
  83880. bodyConfig.posShape.push(0, 0, 0);
  83881. //tmp solution
  83882. bodyConfig.rot.push(rot.x * radToDeg);
  83883. bodyConfig.rot.push(rot.y * radToDeg);
  83884. bodyConfig.rot.push(rot.z * radToDeg);
  83885. bodyConfig.rotShape.push(0, 0, 0);
  83886. }
  83887. else {
  83888. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83889. bodyConfig.posShape.push(localPosition.x);
  83890. bodyConfig.posShape.push(localPosition.y);
  83891. bodyConfig.posShape.push(localPosition.z);
  83892. bodyConfig.pos.push(0, 0, 0);
  83893. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83894. bodyConfig.rot.push(0);
  83895. bodyConfig.rot.push(0);
  83896. bodyConfig.rot.push(0);
  83897. bodyConfig.rotShape.push(rot.x * radToDeg);
  83898. bodyConfig.rotShape.push(rot.y * radToDeg);
  83899. bodyConfig.rotShape.push(rot.z * radToDeg);
  83900. }
  83901. // register mesh
  83902. switch (i.type) {
  83903. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83904. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83905. case BABYLON.PhysicsImpostor.SphereImpostor:
  83906. var radiusX = extendSize.x;
  83907. var radiusY = extendSize.y;
  83908. var radiusZ = extendSize.z;
  83909. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83910. bodyConfig.type.push('sphere');
  83911. //due to the way oimo works with compounds, add 3 times
  83912. bodyConfig.size.push(size);
  83913. bodyConfig.size.push(size);
  83914. bodyConfig.size.push(size);
  83915. break;
  83916. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83917. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83918. var sizeY = checkWithEpsilon_1(extendSize.y);
  83919. bodyConfig.type.push('cylinder');
  83920. bodyConfig.size.push(sizeX);
  83921. bodyConfig.size.push(sizeY);
  83922. //due to the way oimo works with compounds, add one more value.
  83923. bodyConfig.size.push(sizeY);
  83924. break;
  83925. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83926. case BABYLON.PhysicsImpostor.BoxImpostor:
  83927. default:
  83928. var sizeX = checkWithEpsilon_1(extendSize.x);
  83929. var sizeY = checkWithEpsilon_1(extendSize.y);
  83930. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83931. bodyConfig.type.push('box');
  83932. //if (i === impostor) {
  83933. bodyConfig.size.push(sizeX);
  83934. bodyConfig.size.push(sizeY);
  83935. bodyConfig.size.push(sizeZ);
  83936. //} else {
  83937. // bodyConfig.size.push(0,0,0);
  83938. //}
  83939. break;
  83940. }
  83941. //actually not needed, but hey...
  83942. i.object.rotationQuaternion = oldQuaternion;
  83943. });
  83944. impostor.physicsBody = this.world.add(bodyConfig);
  83945. }
  83946. else {
  83947. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83948. }
  83949. impostor.setDeltaPosition(this._tmpPositionVector);
  83950. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83951. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83952. };
  83953. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83954. //impostor.physicsBody.dispose();
  83955. //Same as : (older oimo versions)
  83956. this.world.removeRigidBody(impostor.physicsBody);
  83957. };
  83958. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83959. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83960. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83961. if (!mainBody || !connectedBody) {
  83962. return;
  83963. }
  83964. var jointData = impostorJoint.joint.jointData;
  83965. var options = jointData.nativeParams || {};
  83966. var type;
  83967. var nativeJointData = {
  83968. body1: mainBody,
  83969. body2: connectedBody,
  83970. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83971. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83972. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83973. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83974. min: options.min,
  83975. max: options.max,
  83976. collision: options.collision || jointData.collision,
  83977. spring: options.spring,
  83978. //supporting older version of Oimo
  83979. world: this.world
  83980. };
  83981. switch (impostorJoint.joint.type) {
  83982. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83983. type = "jointBall";
  83984. break;
  83985. case BABYLON.PhysicsJoint.SpringJoint:
  83986. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83987. var springData = jointData;
  83988. nativeJointData.min = springData.length || nativeJointData.min;
  83989. //Max should also be set, just make sure it is at least min
  83990. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83991. case BABYLON.PhysicsJoint.DistanceJoint:
  83992. type = "jointDistance";
  83993. nativeJointData.max = jointData.maxDistance;
  83994. break;
  83995. case BABYLON.PhysicsJoint.PrismaticJoint:
  83996. type = "jointPrisme";
  83997. break;
  83998. case BABYLON.PhysicsJoint.SliderJoint:
  83999. type = "jointSlide";
  84000. break;
  84001. case BABYLON.PhysicsJoint.WheelJoint:
  84002. type = "jointWheel";
  84003. break;
  84004. case BABYLON.PhysicsJoint.HingeJoint:
  84005. default:
  84006. type = "jointHinge";
  84007. break;
  84008. }
  84009. nativeJointData.type = type;
  84010. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84011. };
  84012. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84013. //Bug in Oimo prevents us from disposing a joint in the playground
  84014. //joint.joint.physicsJoint.dispose();
  84015. //So we will bruteforce it!
  84016. try {
  84017. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84018. }
  84019. catch (e) {
  84020. BABYLON.Tools.Warn(e);
  84021. }
  84022. };
  84023. OimoJSPlugin.prototype.isSupported = function () {
  84024. return this.BJSOIMO !== undefined;
  84025. };
  84026. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84027. if (!impostor.physicsBody.sleeping) {
  84028. //TODO check that
  84029. /*if (impostor.physicsBody.shapes.next) {
  84030. var parentShape = this._getLastShape(impostor.physicsBody);
  84031. impostor.object.position.copyFrom(parentShape.position);
  84032. console.log(parentShape.position);
  84033. } else {*/
  84034. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84035. //}
  84036. if (impostor.object.rotationQuaternion) {
  84037. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84038. }
  84039. }
  84040. };
  84041. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84042. var body = impostor.physicsBody;
  84043. body.position.copy(newPosition);
  84044. body.orientation.copy(newRotation);
  84045. body.syncShapes();
  84046. body.awake();
  84047. };
  84048. /*private _getLastShape(body: any): any {
  84049. var lastShape = body.shapes;
  84050. while (lastShape.next) {
  84051. lastShape = lastShape.next;
  84052. }
  84053. return lastShape;
  84054. }*/
  84055. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84056. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84057. };
  84058. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84059. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84060. };
  84061. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84062. var v = impostor.physicsBody.linearVelocity;
  84063. if (!v) {
  84064. return null;
  84065. }
  84066. return new BABYLON.Vector3(v.x, v.y, v.z);
  84067. };
  84068. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84069. var v = impostor.physicsBody.angularVelocity;
  84070. if (!v) {
  84071. return null;
  84072. }
  84073. return new BABYLON.Vector3(v.x, v.y, v.z);
  84074. };
  84075. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84076. var staticBody = mass === 0;
  84077. //this will actually set the body's density and not its mass.
  84078. //But this is how oimo treats the mass variable.
  84079. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84080. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84081. };
  84082. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84083. return impostor.physicsBody.shapes.density;
  84084. };
  84085. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84086. return impostor.physicsBody.shapes.friction;
  84087. };
  84088. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84089. impostor.physicsBody.shapes.friction = friction;
  84090. };
  84091. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84092. return impostor.physicsBody.shapes.restitution;
  84093. };
  84094. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84095. impostor.physicsBody.shapes.restitution = restitution;
  84096. };
  84097. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84098. impostor.physicsBody.sleep();
  84099. };
  84100. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84101. impostor.physicsBody.awake();
  84102. };
  84103. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84104. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84105. if (minDistance !== void 0) {
  84106. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84107. }
  84108. };
  84109. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84110. //TODO separate rotational and transational motors.
  84111. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84112. if (motor) {
  84113. motor.setMotor(speed, maxForce);
  84114. }
  84115. };
  84116. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84117. //TODO separate rotational and transational motors.
  84118. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84119. if (motor) {
  84120. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84121. }
  84122. };
  84123. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84124. var body = impostor.physicsBody;
  84125. mesh.position.x = body.position.x;
  84126. mesh.position.y = body.position.y;
  84127. mesh.position.z = body.position.z;
  84128. if (mesh.rotationQuaternion) {
  84129. mesh.rotationQuaternion.x = body.orientation.x;
  84130. mesh.rotationQuaternion.y = body.orientation.y;
  84131. mesh.rotationQuaternion.z = body.orientation.z;
  84132. mesh.rotationQuaternion.w = body.orientation.s;
  84133. }
  84134. };
  84135. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84136. return impostor.physicsBody.shapes.radius;
  84137. };
  84138. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84139. var shape = impostor.physicsBody.shapes;
  84140. result.x = shape.halfWidth * 2;
  84141. result.y = shape.halfHeight * 2;
  84142. result.z = shape.halfDepth * 2;
  84143. };
  84144. OimoJSPlugin.prototype.dispose = function () {
  84145. this.world.clear();
  84146. };
  84147. return OimoJSPlugin;
  84148. }());
  84149. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84150. })(BABYLON || (BABYLON = {}));
  84151. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84152. var BABYLON;
  84153. (function (BABYLON) {
  84154. /*
  84155. * Based on jsTGALoader - Javascript loader for TGA file
  84156. * By Vincent Thibault
  84157. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84158. */
  84159. var TGATools = /** @class */ (function () {
  84160. function TGATools() {
  84161. }
  84162. TGATools.GetTGAHeader = function (data) {
  84163. var offset = 0;
  84164. var header = {
  84165. id_length: data[offset++],
  84166. colormap_type: data[offset++],
  84167. image_type: data[offset++],
  84168. colormap_index: data[offset++] | data[offset++] << 8,
  84169. colormap_length: data[offset++] | data[offset++] << 8,
  84170. colormap_size: data[offset++],
  84171. origin: [
  84172. data[offset++] | data[offset++] << 8,
  84173. data[offset++] | data[offset++] << 8
  84174. ],
  84175. width: data[offset++] | data[offset++] << 8,
  84176. height: data[offset++] | data[offset++] << 8,
  84177. pixel_size: data[offset++],
  84178. flags: data[offset++]
  84179. };
  84180. return header;
  84181. };
  84182. TGATools.UploadContent = function (gl, data) {
  84183. // Not enough data to contain header ?
  84184. if (data.length < 19) {
  84185. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84186. return;
  84187. }
  84188. // Read Header
  84189. var offset = 18;
  84190. var header = TGATools.GetTGAHeader(data);
  84191. // Assume it's a valid Targa file.
  84192. if (header.id_length + offset > data.length) {
  84193. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84194. return;
  84195. }
  84196. // Skip not needed data
  84197. offset += header.id_length;
  84198. var use_rle = false;
  84199. var use_pal = false;
  84200. var use_grey = false;
  84201. // Get some informations.
  84202. switch (header.image_type) {
  84203. case TGATools._TYPE_RLE_INDEXED:
  84204. use_rle = true;
  84205. case TGATools._TYPE_INDEXED:
  84206. use_pal = true;
  84207. break;
  84208. case TGATools._TYPE_RLE_RGB:
  84209. use_rle = true;
  84210. case TGATools._TYPE_RGB:
  84211. // use_rgb = true;
  84212. break;
  84213. case TGATools._TYPE_RLE_GREY:
  84214. use_rle = true;
  84215. case TGATools._TYPE_GREY:
  84216. use_grey = true;
  84217. break;
  84218. }
  84219. var pixel_data;
  84220. // var numAlphaBits = header.flags & 0xf;
  84221. var pixel_size = header.pixel_size >> 3;
  84222. var pixel_total = header.width * header.height * pixel_size;
  84223. // Read palettes
  84224. var palettes;
  84225. if (use_pal) {
  84226. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84227. }
  84228. // Read LRE
  84229. if (use_rle) {
  84230. pixel_data = new Uint8Array(pixel_total);
  84231. var c, count, i;
  84232. var localOffset = 0;
  84233. var pixels = new Uint8Array(pixel_size);
  84234. while (offset < pixel_total && localOffset < pixel_total) {
  84235. c = data[offset++];
  84236. count = (c & 0x7f) + 1;
  84237. // RLE pixels
  84238. if (c & 0x80) {
  84239. // Bind pixel tmp array
  84240. for (i = 0; i < pixel_size; ++i) {
  84241. pixels[i] = data[offset++];
  84242. }
  84243. // Copy pixel array
  84244. for (i = 0; i < count; ++i) {
  84245. pixel_data.set(pixels, localOffset + i * pixel_size);
  84246. }
  84247. localOffset += pixel_size * count;
  84248. }
  84249. // Raw pixels
  84250. else {
  84251. count *= pixel_size;
  84252. for (i = 0; i < count; ++i) {
  84253. pixel_data[localOffset + i] = data[offset++];
  84254. }
  84255. localOffset += count;
  84256. }
  84257. }
  84258. }
  84259. // RAW Pixels
  84260. else {
  84261. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84262. }
  84263. // Load to texture
  84264. var x_start, y_start, x_step, y_step, y_end, x_end;
  84265. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84266. default:
  84267. case TGATools._ORIGIN_UL:
  84268. x_start = 0;
  84269. x_step = 1;
  84270. x_end = header.width;
  84271. y_start = 0;
  84272. y_step = 1;
  84273. y_end = header.height;
  84274. break;
  84275. case TGATools._ORIGIN_BL:
  84276. x_start = 0;
  84277. x_step = 1;
  84278. x_end = header.width;
  84279. y_start = header.height - 1;
  84280. y_step = -1;
  84281. y_end = -1;
  84282. break;
  84283. case TGATools._ORIGIN_UR:
  84284. x_start = header.width - 1;
  84285. x_step = -1;
  84286. x_end = -1;
  84287. y_start = 0;
  84288. y_step = 1;
  84289. y_end = header.height;
  84290. break;
  84291. case TGATools._ORIGIN_BR:
  84292. x_start = header.width - 1;
  84293. x_step = -1;
  84294. x_end = -1;
  84295. y_start = header.height - 1;
  84296. y_step = -1;
  84297. y_end = -1;
  84298. break;
  84299. }
  84300. // Load the specify method
  84301. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84302. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84303. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84304. };
  84305. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84306. var image = pixel_data, colormap = palettes;
  84307. var width = header.width, height = header.height;
  84308. var color, i = 0, x, y;
  84309. var imageData = new Uint8Array(width * height * 4);
  84310. for (y = y_start; y !== y_end; y += y_step) {
  84311. for (x = x_start; x !== x_end; x += x_step, i++) {
  84312. color = image[i];
  84313. imageData[(x + width * y) * 4 + 3] = 255;
  84314. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84315. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84316. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84317. }
  84318. }
  84319. return imageData;
  84320. };
  84321. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84322. var image = pixel_data;
  84323. var width = header.width, height = header.height;
  84324. var color, i = 0, x, y;
  84325. var imageData = new Uint8Array(width * height * 4);
  84326. for (y = y_start; y !== y_end; y += y_step) {
  84327. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84328. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84329. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84330. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84331. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84332. imageData[(x + width * y) * 4 + 0] = r;
  84333. imageData[(x + width * y) * 4 + 1] = g;
  84334. imageData[(x + width * y) * 4 + 2] = b;
  84335. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84336. }
  84337. }
  84338. return imageData;
  84339. };
  84340. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84341. var image = pixel_data;
  84342. var width = header.width, height = header.height;
  84343. var i = 0, x, y;
  84344. var imageData = new Uint8Array(width * height * 4);
  84345. for (y = y_start; y !== y_end; y += y_step) {
  84346. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84347. imageData[(x + width * y) * 4 + 3] = 255;
  84348. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84349. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84350. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84351. }
  84352. }
  84353. return imageData;
  84354. };
  84355. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84356. var image = pixel_data;
  84357. var width = header.width, height = header.height;
  84358. var i = 0, x, y;
  84359. var imageData = new Uint8Array(width * height * 4);
  84360. for (y = y_start; y !== y_end; y += y_step) {
  84361. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84362. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84363. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84364. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84365. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84366. }
  84367. }
  84368. return imageData;
  84369. };
  84370. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84371. var image = pixel_data;
  84372. var width = header.width, height = header.height;
  84373. var color, i = 0, x, y;
  84374. var imageData = new Uint8Array(width * height * 4);
  84375. for (y = y_start; y !== y_end; y += y_step) {
  84376. for (x = x_start; x !== x_end; x += x_step, i++) {
  84377. color = image[i];
  84378. imageData[(x + width * y) * 4 + 0] = color;
  84379. imageData[(x + width * y) * 4 + 1] = color;
  84380. imageData[(x + width * y) * 4 + 2] = color;
  84381. imageData[(x + width * y) * 4 + 3] = 255;
  84382. }
  84383. }
  84384. return imageData;
  84385. };
  84386. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84387. var image = pixel_data;
  84388. var width = header.width, height = header.height;
  84389. var i = 0, x, y;
  84390. var imageData = new Uint8Array(width * height * 4);
  84391. for (y = y_start; y !== y_end; y += y_step) {
  84392. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84393. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84394. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84395. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84396. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84397. }
  84398. }
  84399. return imageData;
  84400. };
  84401. //private static _TYPE_NO_DATA = 0;
  84402. TGATools._TYPE_INDEXED = 1;
  84403. TGATools._TYPE_RGB = 2;
  84404. TGATools._TYPE_GREY = 3;
  84405. TGATools._TYPE_RLE_INDEXED = 9;
  84406. TGATools._TYPE_RLE_RGB = 10;
  84407. TGATools._TYPE_RLE_GREY = 11;
  84408. TGATools._ORIGIN_MASK = 0x30;
  84409. TGATools._ORIGIN_SHIFT = 0x04;
  84410. TGATools._ORIGIN_BL = 0x00;
  84411. TGATools._ORIGIN_BR = 0x01;
  84412. TGATools._ORIGIN_UL = 0x02;
  84413. TGATools._ORIGIN_UR = 0x03;
  84414. return TGATools;
  84415. }());
  84416. BABYLON.TGATools = TGATools;
  84417. })(BABYLON || (BABYLON = {}));
  84418. //# sourceMappingURL=babylon.tga.js.map
  84419. var BABYLON;
  84420. (function (BABYLON) {
  84421. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84422. // All values and structures referenced from:
  84423. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84424. var DDS_MAGIC = 0x20534444;
  84425. var
  84426. //DDSD_CAPS = 0x1,
  84427. //DDSD_HEIGHT = 0x2,
  84428. //DDSD_WIDTH = 0x4,
  84429. //DDSD_PITCH = 0x8,
  84430. //DDSD_PIXELFORMAT = 0x1000,
  84431. DDSD_MIPMAPCOUNT = 0x20000;
  84432. //DDSD_LINEARSIZE = 0x80000,
  84433. //DDSD_DEPTH = 0x800000;
  84434. // var DDSCAPS_COMPLEX = 0x8,
  84435. // DDSCAPS_MIPMAP = 0x400000,
  84436. // DDSCAPS_TEXTURE = 0x1000;
  84437. var DDSCAPS2_CUBEMAP = 0x200;
  84438. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84439. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84440. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84441. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84442. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84443. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84444. // DDSCAPS2_VOLUME = 0x200000;
  84445. var
  84446. //DDPF_ALPHAPIXELS = 0x1,
  84447. //DDPF_ALPHA = 0x2,
  84448. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84449. //DDPF_YUV = 0x200,
  84450. DDPF_LUMINANCE = 0x20000;
  84451. function FourCCToInt32(value) {
  84452. return value.charCodeAt(0) +
  84453. (value.charCodeAt(1) << 8) +
  84454. (value.charCodeAt(2) << 16) +
  84455. (value.charCodeAt(3) << 24);
  84456. }
  84457. function Int32ToFourCC(value) {
  84458. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84459. }
  84460. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84461. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84462. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84463. var FOURCC_DX10 = FourCCToInt32("DX10");
  84464. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84465. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84466. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84467. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84468. var headerLengthInt = 31; // The header length in 32 bit ints
  84469. // Offsets into the header array
  84470. var off_magic = 0;
  84471. var off_size = 1;
  84472. var off_flags = 2;
  84473. var off_height = 3;
  84474. var off_width = 4;
  84475. var off_mipmapCount = 7;
  84476. var off_pfFlags = 20;
  84477. var off_pfFourCC = 21;
  84478. var off_RGBbpp = 22;
  84479. var off_RMask = 23;
  84480. var off_GMask = 24;
  84481. var off_BMask = 25;
  84482. var off_AMask = 26;
  84483. // var off_caps1 = 27;
  84484. var off_caps2 = 28;
  84485. // var off_caps3 = 29;
  84486. // var off_caps4 = 30;
  84487. var off_dxgiFormat = 32;
  84488. ;
  84489. var DDSTools = /** @class */ (function () {
  84490. function DDSTools() {
  84491. }
  84492. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84493. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84494. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84495. var mipmapCount = 1;
  84496. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84497. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84498. }
  84499. var fourCC = header[off_pfFourCC];
  84500. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84501. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84502. switch (fourCC) {
  84503. case FOURCC_D3DFMT_R16G16B16A16F:
  84504. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84505. break;
  84506. case FOURCC_D3DFMT_R32G32B32A32F:
  84507. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84508. break;
  84509. case FOURCC_DX10:
  84510. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84511. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84512. break;
  84513. }
  84514. }
  84515. return {
  84516. width: header[off_width],
  84517. height: header[off_height],
  84518. mipmapCount: mipmapCount,
  84519. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84520. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84521. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84522. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84523. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84524. dxgiFormat: dxgiFormat,
  84525. textureType: textureType
  84526. };
  84527. };
  84528. DDSTools._ToHalfFloat = function (value) {
  84529. if (!DDSTools._FloatView) {
  84530. DDSTools._FloatView = new Float32Array(1);
  84531. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84532. }
  84533. DDSTools._FloatView[0] = value;
  84534. var x = DDSTools._Int32View[0];
  84535. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84536. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84537. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84538. /* If zero, or denormal, or exponent underflows too much for a denormal
  84539. * half, return signed zero. */
  84540. if (e < 103) {
  84541. return bits;
  84542. }
  84543. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84544. if (e > 142) {
  84545. bits |= 0x7c00;
  84546. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84547. * not Inf, so make sure we set one mantissa bit too. */
  84548. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84549. return bits;
  84550. }
  84551. /* If exponent underflows but not too much, return a denormal */
  84552. if (e < 113) {
  84553. m |= 0x0800;
  84554. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84555. * to 1, which is OK. */
  84556. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84557. return bits;
  84558. }
  84559. bits |= ((e - 112) << 10) | (m >> 1);
  84560. bits += m & 1;
  84561. return bits;
  84562. };
  84563. DDSTools._FromHalfFloat = function (value) {
  84564. var s = (value & 0x8000) >> 15;
  84565. var e = (value & 0x7C00) >> 10;
  84566. var f = value & 0x03FF;
  84567. if (e === 0) {
  84568. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84569. }
  84570. else if (e == 0x1F) {
  84571. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84572. }
  84573. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84574. };
  84575. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84576. var destArray = new Float32Array(dataLength);
  84577. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84578. var index = 0;
  84579. for (var y = 0; y < height; y++) {
  84580. for (var x = 0; x < width; x++) {
  84581. var srcPos = (x + y * width) * 4;
  84582. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84583. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84584. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84585. if (DDSTools.StoreLODInAlphaChannel) {
  84586. destArray[index + 3] = lod;
  84587. }
  84588. else {
  84589. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84590. }
  84591. index += 4;
  84592. }
  84593. }
  84594. return destArray;
  84595. };
  84596. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84597. if (DDSTools.StoreLODInAlphaChannel) {
  84598. var destArray = new Uint16Array(dataLength);
  84599. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84600. var index = 0;
  84601. for (var y = 0; y < height; y++) {
  84602. for (var x = 0; x < width; x++) {
  84603. var srcPos = (x + y * width) * 4;
  84604. destArray[index] = srcData[srcPos];
  84605. destArray[index + 1] = srcData[srcPos + 1];
  84606. destArray[index + 2] = srcData[srcPos + 2];
  84607. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84608. index += 4;
  84609. }
  84610. }
  84611. return destArray;
  84612. }
  84613. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84614. };
  84615. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84616. if (DDSTools.StoreLODInAlphaChannel) {
  84617. var destArray = new Float32Array(dataLength);
  84618. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84619. var index = 0;
  84620. for (var y = 0; y < height; y++) {
  84621. for (var x = 0; x < width; x++) {
  84622. var srcPos = (x + y * width) * 4;
  84623. destArray[index] = srcData[srcPos];
  84624. destArray[index + 1] = srcData[srcPos + 1];
  84625. destArray[index + 2] = srcData[srcPos + 2];
  84626. destArray[index + 3] = lod;
  84627. index += 4;
  84628. }
  84629. }
  84630. return destArray;
  84631. }
  84632. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84633. };
  84634. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84635. var destArray = new Uint8Array(dataLength);
  84636. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84637. var index = 0;
  84638. for (var y = 0; y < height; y++) {
  84639. for (var x = 0; x < width; x++) {
  84640. var srcPos = (x + y * width) * 4;
  84641. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84642. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84643. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84644. if (DDSTools.StoreLODInAlphaChannel) {
  84645. destArray[index + 3] = lod;
  84646. }
  84647. else {
  84648. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84649. }
  84650. index += 4;
  84651. }
  84652. }
  84653. return destArray;
  84654. };
  84655. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84656. var destArray = new Uint8Array(dataLength);
  84657. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84658. var index = 0;
  84659. for (var y = 0; y < height; y++) {
  84660. for (var x = 0; x < width; x++) {
  84661. var srcPos = (x + y * width) * 4;
  84662. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84663. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84664. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84665. if (DDSTools.StoreLODInAlphaChannel) {
  84666. destArray[index + 3] = lod;
  84667. }
  84668. else {
  84669. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84670. }
  84671. index += 4;
  84672. }
  84673. }
  84674. return destArray;
  84675. };
  84676. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84677. var byteArray = new Uint8Array(dataLength);
  84678. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84679. var index = 0;
  84680. for (var y = 0; y < height; y++) {
  84681. for (var x = 0; x < width; x++) {
  84682. var srcPos = (x + y * width) * 4;
  84683. byteArray[index] = srcData[srcPos + rOffset];
  84684. byteArray[index + 1] = srcData[srcPos + gOffset];
  84685. byteArray[index + 2] = srcData[srcPos + bOffset];
  84686. byteArray[index + 3] = srcData[srcPos + aOffset];
  84687. index += 4;
  84688. }
  84689. }
  84690. return byteArray;
  84691. };
  84692. DDSTools._ExtractLongWordOrder = function (value) {
  84693. if (value === 0 || value === 255 || value === -16777216) {
  84694. return 0;
  84695. }
  84696. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84697. };
  84698. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84699. var byteArray = new Uint8Array(dataLength);
  84700. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84701. var index = 0;
  84702. for (var y = 0; y < height; y++) {
  84703. for (var x = 0; x < width; x++) {
  84704. var srcPos = (x + y * width) * 3;
  84705. byteArray[index] = srcData[srcPos + rOffset];
  84706. byteArray[index + 1] = srcData[srcPos + gOffset];
  84707. byteArray[index + 2] = srcData[srcPos + bOffset];
  84708. index += 3;
  84709. }
  84710. }
  84711. return byteArray;
  84712. };
  84713. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84714. var byteArray = new Uint8Array(dataLength);
  84715. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84716. var index = 0;
  84717. for (var y = 0; y < height; y++) {
  84718. for (var x = 0; x < width; x++) {
  84719. var srcPos = (x + y * width);
  84720. byteArray[index] = srcData[srcPos];
  84721. index++;
  84722. }
  84723. }
  84724. return byteArray;
  84725. };
  84726. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84727. if (lodIndex === void 0) { lodIndex = -1; }
  84728. var sphericalPolynomialFaces = null;
  84729. if (info.sphericalPolynomial) {
  84730. sphericalPolynomialFaces = new Array();
  84731. }
  84732. var ext = engine.getCaps().s3tc;
  84733. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84734. var fourCC, width, height, dataLength = 0, dataOffset;
  84735. var byteArray, mipmapCount, mip;
  84736. var internalFormat = 0;
  84737. var format = 0;
  84738. var blockBytes = 1;
  84739. if (header[off_magic] !== DDS_MAGIC) {
  84740. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84741. return;
  84742. }
  84743. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84744. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84745. return;
  84746. }
  84747. if (info.isCompressed && !ext) {
  84748. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84749. return;
  84750. }
  84751. var bpp = header[off_RGBbpp];
  84752. dataOffset = header[off_size] + 4;
  84753. var computeFormats = false;
  84754. if (info.isFourCC) {
  84755. fourCC = header[off_pfFourCC];
  84756. switch (fourCC) {
  84757. case FOURCC_DXT1:
  84758. blockBytes = 8;
  84759. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84760. break;
  84761. case FOURCC_DXT3:
  84762. blockBytes = 16;
  84763. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84764. break;
  84765. case FOURCC_DXT5:
  84766. blockBytes = 16;
  84767. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84768. break;
  84769. case FOURCC_D3DFMT_R16G16B16A16F:
  84770. computeFormats = true;
  84771. break;
  84772. case FOURCC_D3DFMT_R32G32B32A32F:
  84773. computeFormats = true;
  84774. break;
  84775. case FOURCC_DX10:
  84776. // There is an additionnal header so dataOffset need to be changed
  84777. dataOffset += 5 * 4; // 5 uints
  84778. var supported = false;
  84779. switch (info.dxgiFormat) {
  84780. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84781. computeFormats = true;
  84782. supported = true;
  84783. break;
  84784. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84785. info.isRGB = true;
  84786. info.isFourCC = false;
  84787. bpp = 32;
  84788. supported = true;
  84789. break;
  84790. }
  84791. if (supported) {
  84792. break;
  84793. }
  84794. default:
  84795. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84796. return;
  84797. }
  84798. }
  84799. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84800. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84801. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84802. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84803. if (computeFormats) {
  84804. format = engine._getWebGLTextureType(info.textureType);
  84805. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84806. }
  84807. mipmapCount = 1;
  84808. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84809. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84810. }
  84811. for (var face = 0; face < faces; face++) {
  84812. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84813. width = header[off_width];
  84814. height = header[off_height];
  84815. for (mip = 0; mip < mipmapCount; ++mip) {
  84816. if (lodIndex === -1 || lodIndex === mip) {
  84817. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84818. var i = (lodIndex === -1) ? mip : 0;
  84819. if (!info.isCompressed && info.isFourCC) {
  84820. dataLength = width * height * 4;
  84821. var floatArray = null;
  84822. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84823. if (bpp === 128) {
  84824. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84825. if (sphericalPolynomialFaces && i == 0) {
  84826. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84827. }
  84828. }
  84829. else if (bpp === 64) {
  84830. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84831. if (sphericalPolynomialFaces && i == 0) {
  84832. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84833. }
  84834. }
  84835. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84836. format = engine._getWebGLTextureType(info.textureType);
  84837. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84838. }
  84839. else {
  84840. if (bpp === 128) {
  84841. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84842. if (sphericalPolynomialFaces && i == 0) {
  84843. sphericalPolynomialFaces.push(floatArray);
  84844. }
  84845. }
  84846. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84847. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84848. if (sphericalPolynomialFaces && i == 0) {
  84849. sphericalPolynomialFaces.push(floatArray);
  84850. }
  84851. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84852. format = engine._getWebGLTextureType(info.textureType);
  84853. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84854. }
  84855. else { // 64
  84856. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84857. if (sphericalPolynomialFaces && i == 0) {
  84858. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84859. }
  84860. }
  84861. }
  84862. if (floatArray) {
  84863. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84864. }
  84865. }
  84866. else if (info.isRGB) {
  84867. if (bpp === 24) {
  84868. dataLength = width * height * 3;
  84869. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84870. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84871. }
  84872. else { // 32
  84873. dataLength = width * height * 4;
  84874. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84875. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84876. }
  84877. }
  84878. else if (info.isLuminance) {
  84879. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84880. var unpaddedRowSize = width;
  84881. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84882. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84883. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84884. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84885. }
  84886. else {
  84887. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84888. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84889. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84890. }
  84891. }
  84892. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84893. width *= 0.5;
  84894. height *= 0.5;
  84895. width = Math.max(1.0, width);
  84896. height = Math.max(1.0, height);
  84897. }
  84898. if (currentFace !== undefined) {
  84899. // Loading a single face
  84900. break;
  84901. }
  84902. }
  84903. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84904. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84905. size: header[off_width],
  84906. right: sphericalPolynomialFaces[0],
  84907. left: sphericalPolynomialFaces[1],
  84908. up: sphericalPolynomialFaces[2],
  84909. down: sphericalPolynomialFaces[3],
  84910. front: sphericalPolynomialFaces[4],
  84911. back: sphericalPolynomialFaces[5],
  84912. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84913. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84914. gammaSpace: false,
  84915. });
  84916. }
  84917. else {
  84918. info.sphericalPolynomial = undefined;
  84919. }
  84920. };
  84921. DDSTools.StoreLODInAlphaChannel = false;
  84922. return DDSTools;
  84923. }());
  84924. BABYLON.DDSTools = DDSTools;
  84925. })(BABYLON || (BABYLON = {}));
  84926. //# sourceMappingURL=babylon.dds.js.map
  84927. var BABYLON;
  84928. (function (BABYLON) {
  84929. /**
  84930. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84931. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84932. */
  84933. var KhronosTextureContainer = /** @class */ (function () {
  84934. /**
  84935. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84936. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84937. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84938. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84939. */
  84940. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84941. this.arrayBuffer = arrayBuffer;
  84942. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84943. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84944. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84945. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84946. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84947. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84948. BABYLON.Tools.Error("texture missing KTX identifier");
  84949. return;
  84950. }
  84951. // load the reset of the header in native 32 bit int
  84952. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84953. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84954. var oppositeEndianess = header[0] === 0x01020304;
  84955. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84956. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84957. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84958. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84959. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84960. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84961. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84962. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84963. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84964. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84965. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84966. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84967. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84968. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84969. if (this.glType !== 0) {
  84970. BABYLON.Tools.Error("only compressed formats currently supported");
  84971. return;
  84972. }
  84973. else {
  84974. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84975. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84976. }
  84977. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84978. BABYLON.Tools.Error("only 2D textures currently supported");
  84979. return;
  84980. }
  84981. if (this.numberOfArrayElements !== 0) {
  84982. BABYLON.Tools.Error("texture arrays not currently supported");
  84983. return;
  84984. }
  84985. if (this.numberOfFaces !== facesExpected) {
  84986. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84987. return;
  84988. }
  84989. // we now have a completely validated file, so could use existence of loadType as success
  84990. // would need to make this more elaborate & adjust checks above to support more than one load type
  84991. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84992. }
  84993. // not as fast hardware based, but will probably never need to use
  84994. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84995. return ((val & 0xFF) << 24)
  84996. | ((val & 0xFF00) << 8)
  84997. | ((val >> 8) & 0xFF00)
  84998. | ((val >> 24) & 0xFF);
  84999. };
  85000. /**
  85001. * It is assumed that the texture has already been created & is currently bound
  85002. */
  85003. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85004. switch (this.loadType) {
  85005. case KhronosTextureContainer.COMPRESSED_2D:
  85006. this._upload2DCompressedLevels(gl, loadMipmaps);
  85007. break;
  85008. case KhronosTextureContainer.TEX_2D:
  85009. case KhronosTextureContainer.COMPRESSED_3D:
  85010. case KhronosTextureContainer.TEX_3D:
  85011. }
  85012. };
  85013. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85014. // initialize width & height for level 1
  85015. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85016. var width = this.pixelWidth;
  85017. var height = this.pixelHeight;
  85018. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85019. for (var level = 0; level < mipmapCount; level++) {
  85020. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85021. for (var face = 0; face < this.numberOfFaces; face++) {
  85022. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85023. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85024. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85025. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85026. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85027. }
  85028. width = Math.max(1.0, width * 0.5);
  85029. height = Math.max(1.0, height * 0.5);
  85030. }
  85031. };
  85032. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85033. // load types
  85034. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85035. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85036. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85037. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85038. return KhronosTextureContainer;
  85039. }());
  85040. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85041. })(BABYLON || (BABYLON = {}));
  85042. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85043. var BABYLON;
  85044. (function (BABYLON) {
  85045. var Debug;
  85046. (function (Debug) {
  85047. /**
  85048. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85049. */
  85050. var SkeletonViewer = /** @class */ (function () {
  85051. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85052. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85053. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85054. this.skeleton = skeleton;
  85055. this.mesh = mesh;
  85056. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85057. this.renderingGroupId = renderingGroupId;
  85058. this.color = BABYLON.Color3.White();
  85059. this._debugLines = new Array();
  85060. this._isEnabled = false;
  85061. this._scene = scene;
  85062. this.update();
  85063. this._renderFunction = this.update.bind(this);
  85064. }
  85065. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85066. get: function () {
  85067. return this._isEnabled;
  85068. },
  85069. set: function (value) {
  85070. if (this._isEnabled === value) {
  85071. return;
  85072. }
  85073. this._isEnabled = value;
  85074. if (value) {
  85075. this._scene.registerBeforeRender(this._renderFunction);
  85076. }
  85077. else {
  85078. this._scene.unregisterBeforeRender(this._renderFunction);
  85079. }
  85080. },
  85081. enumerable: true,
  85082. configurable: true
  85083. });
  85084. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85085. if (x === void 0) { x = 0; }
  85086. if (y === void 0) { y = 0; }
  85087. if (z === void 0) { z = 0; }
  85088. var tmat = BABYLON.Tmp.Matrix[0];
  85089. var parentBone = bone.getParent();
  85090. tmat.copyFrom(bone.getLocalMatrix());
  85091. if (x !== 0 || y !== 0 || z !== 0) {
  85092. var tmat2 = BABYLON.Tmp.Matrix[1];
  85093. BABYLON.Matrix.IdentityToRef(tmat2);
  85094. tmat2.m[12] = x;
  85095. tmat2.m[13] = y;
  85096. tmat2.m[14] = z;
  85097. tmat2.multiplyToRef(tmat, tmat);
  85098. }
  85099. if (parentBone) {
  85100. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85101. }
  85102. tmat.multiplyToRef(meshMat, tmat);
  85103. position.x = tmat.m[12];
  85104. position.y = tmat.m[13];
  85105. position.z = tmat.m[14];
  85106. };
  85107. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85108. var len = bones.length;
  85109. var meshPos = this.mesh.position;
  85110. for (var i = 0; i < len; i++) {
  85111. var bone = bones[i];
  85112. var points = this._debugLines[i];
  85113. if (!points) {
  85114. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85115. this._debugLines[i] = points;
  85116. }
  85117. this._getBonePosition(points[0], bone, meshMat);
  85118. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85119. points[0].subtractInPlace(meshPos);
  85120. points[1].subtractInPlace(meshPos);
  85121. }
  85122. };
  85123. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85124. var len = bones.length;
  85125. var boneNum = 0;
  85126. var meshPos = this.mesh.position;
  85127. for (var i = len - 1; i >= 0; i--) {
  85128. var childBone = bones[i];
  85129. var parentBone = childBone.getParent();
  85130. if (!parentBone) {
  85131. continue;
  85132. }
  85133. var points = this._debugLines[boneNum];
  85134. if (!points) {
  85135. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85136. this._debugLines[boneNum] = points;
  85137. }
  85138. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85139. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85140. points[0].subtractInPlace(meshPos);
  85141. points[1].subtractInPlace(meshPos);
  85142. boneNum++;
  85143. }
  85144. };
  85145. SkeletonViewer.prototype.update = function () {
  85146. if (this.autoUpdateBonesMatrices) {
  85147. this.skeleton.computeAbsoluteTransforms();
  85148. }
  85149. if (this.skeleton.bones[0].length === undefined) {
  85150. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85151. }
  85152. else {
  85153. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85154. }
  85155. if (!this._debugMesh) {
  85156. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85157. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85158. }
  85159. else {
  85160. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85161. }
  85162. this._debugMesh.position.copyFrom(this.mesh.position);
  85163. this._debugMesh.color = this.color;
  85164. };
  85165. SkeletonViewer.prototype.dispose = function () {
  85166. if (this._debugMesh) {
  85167. this.isEnabled = false;
  85168. this._debugMesh.dispose();
  85169. this._debugMesh = null;
  85170. }
  85171. };
  85172. return SkeletonViewer;
  85173. }());
  85174. Debug.SkeletonViewer = SkeletonViewer;
  85175. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85176. })(BABYLON || (BABYLON = {}));
  85177. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85178. /**
  85179. * Module Debug contains the (visual) components to debug a scene correctly
  85180. */
  85181. var BABYLON;
  85182. (function (BABYLON) {
  85183. var Debug;
  85184. (function (Debug) {
  85185. /**
  85186. * The Axes viewer will show 3 axes in a specific point in space
  85187. */
  85188. var AxesViewer = /** @class */ (function () {
  85189. function AxesViewer(scene, scaleLines) {
  85190. if (scaleLines === void 0) { scaleLines = 1; }
  85191. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85192. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85193. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85194. this.scaleLines = 1;
  85195. this.scaleLines = scaleLines;
  85196. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85197. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85198. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85199. this._xmesh.renderingGroupId = 2;
  85200. this._ymesh.renderingGroupId = 2;
  85201. this._zmesh.renderingGroupId = 2;
  85202. this._xmesh.material.checkReadyOnlyOnce = true;
  85203. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85204. this._ymesh.material.checkReadyOnlyOnce = true;
  85205. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85206. this._zmesh.material.checkReadyOnlyOnce = true;
  85207. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85208. this.scene = scene;
  85209. }
  85210. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85211. var scaleLines = this.scaleLines;
  85212. if (this._xmesh) {
  85213. this._xmesh.position.copyFrom(position);
  85214. }
  85215. if (this._ymesh) {
  85216. this._ymesh.position.copyFrom(position);
  85217. }
  85218. if (this._zmesh) {
  85219. this._zmesh.position.copyFrom(position);
  85220. }
  85221. var point2 = this._xline[1];
  85222. point2.x = xaxis.x * scaleLines;
  85223. point2.y = xaxis.y * scaleLines;
  85224. point2.z = xaxis.z * scaleLines;
  85225. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85226. point2 = this._yline[1];
  85227. point2.x = yaxis.x * scaleLines;
  85228. point2.y = yaxis.y * scaleLines;
  85229. point2.z = yaxis.z * scaleLines;
  85230. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85231. point2 = this._zline[1];
  85232. point2.x = zaxis.x * scaleLines;
  85233. point2.y = zaxis.y * scaleLines;
  85234. point2.z = zaxis.z * scaleLines;
  85235. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85236. };
  85237. AxesViewer.prototype.dispose = function () {
  85238. if (this._xmesh) {
  85239. this._xmesh.dispose();
  85240. }
  85241. if (this._ymesh) {
  85242. this._ymesh.dispose();
  85243. }
  85244. if (this._zmesh) {
  85245. this._zmesh.dispose();
  85246. }
  85247. this._xmesh = null;
  85248. this._ymesh = null;
  85249. this._zmesh = null;
  85250. this.scene = null;
  85251. };
  85252. return AxesViewer;
  85253. }());
  85254. Debug.AxesViewer = AxesViewer;
  85255. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85256. })(BABYLON || (BABYLON = {}));
  85257. //# sourceMappingURL=babylon.axesViewer.js.map
  85258. var BABYLON;
  85259. (function (BABYLON) {
  85260. var Debug;
  85261. (function (Debug) {
  85262. /**
  85263. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85264. */
  85265. var BoneAxesViewer = /** @class */ (function (_super) {
  85266. __extends(BoneAxesViewer, _super);
  85267. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85268. if (scaleLines === void 0) { scaleLines = 1; }
  85269. var _this = _super.call(this, scene, scaleLines) || this;
  85270. _this.pos = BABYLON.Vector3.Zero();
  85271. _this.xaxis = BABYLON.Vector3.Zero();
  85272. _this.yaxis = BABYLON.Vector3.Zero();
  85273. _this.zaxis = BABYLON.Vector3.Zero();
  85274. _this.mesh = mesh;
  85275. _this.bone = bone;
  85276. return _this;
  85277. }
  85278. BoneAxesViewer.prototype.update = function () {
  85279. if (!this.mesh || !this.bone) {
  85280. return;
  85281. }
  85282. var bone = this.bone;
  85283. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85284. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85285. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85286. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85287. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85288. };
  85289. BoneAxesViewer.prototype.dispose = function () {
  85290. if (this.mesh) {
  85291. this.mesh = null;
  85292. this.bone = null;
  85293. _super.prototype.dispose.call(this);
  85294. }
  85295. };
  85296. return BoneAxesViewer;
  85297. }(Debug.AxesViewer));
  85298. Debug.BoneAxesViewer = BoneAxesViewer;
  85299. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85300. })(BABYLON || (BABYLON = {}));
  85301. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85302. var BABYLON;
  85303. (function (BABYLON) {
  85304. var RayHelper = /** @class */ (function () {
  85305. function RayHelper(ray) {
  85306. this.ray = ray;
  85307. }
  85308. RayHelper.CreateAndShow = function (ray, scene, color) {
  85309. var helper = new RayHelper(ray);
  85310. helper.show(scene, color);
  85311. return helper;
  85312. };
  85313. RayHelper.prototype.show = function (scene, color) {
  85314. if (!this._renderFunction && this.ray) {
  85315. var ray = this.ray;
  85316. this._renderFunction = this._render.bind(this);
  85317. this._scene = scene;
  85318. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85319. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85320. if (this._renderFunction) {
  85321. this._scene.registerBeforeRender(this._renderFunction);
  85322. }
  85323. }
  85324. if (color && this._renderLine) {
  85325. this._renderLine.color.copyFrom(color);
  85326. }
  85327. };
  85328. RayHelper.prototype.hide = function () {
  85329. if (this._renderFunction && this._scene) {
  85330. this._scene.unregisterBeforeRender(this._renderFunction);
  85331. this._scene = null;
  85332. this._renderFunction = null;
  85333. if (this._renderLine) {
  85334. this._renderLine.dispose();
  85335. this._renderLine = null;
  85336. }
  85337. this._renderPoints = [];
  85338. }
  85339. };
  85340. RayHelper.prototype._render = function () {
  85341. var ray = this.ray;
  85342. if (!ray) {
  85343. return;
  85344. }
  85345. var point = this._renderPoints[1];
  85346. var len = Math.min(ray.length, 1000000);
  85347. point.copyFrom(ray.direction);
  85348. point.scaleInPlace(len);
  85349. point.addInPlace(ray.origin);
  85350. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85351. };
  85352. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85353. this._attachedToMesh = mesh;
  85354. var ray = this.ray;
  85355. if (!ray) {
  85356. return;
  85357. }
  85358. if (!ray.direction) {
  85359. ray.direction = BABYLON.Vector3.Zero();
  85360. }
  85361. if (!ray.origin) {
  85362. ray.origin = BABYLON.Vector3.Zero();
  85363. }
  85364. if (length) {
  85365. ray.length = length;
  85366. }
  85367. if (!meshSpaceOrigin) {
  85368. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85369. }
  85370. if (!meshSpaceDirection) {
  85371. // -1 so that this will work with Mesh.lookAt
  85372. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85373. }
  85374. if (!this._meshSpaceDirection) {
  85375. this._meshSpaceDirection = meshSpaceDirection.clone();
  85376. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85377. }
  85378. else {
  85379. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85380. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85381. }
  85382. if (!this._updateToMeshFunction) {
  85383. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85384. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85385. }
  85386. this._updateToMesh();
  85387. };
  85388. RayHelper.prototype.detachFromMesh = function () {
  85389. if (this._attachedToMesh) {
  85390. if (this._updateToMeshFunction) {
  85391. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85392. }
  85393. this._attachedToMesh = null;
  85394. this._updateToMeshFunction = null;
  85395. }
  85396. };
  85397. RayHelper.prototype._updateToMesh = function () {
  85398. var ray = this.ray;
  85399. if (!this._attachedToMesh || !ray) {
  85400. return;
  85401. }
  85402. if (this._attachedToMesh._isDisposed) {
  85403. this.detachFromMesh();
  85404. return;
  85405. }
  85406. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85407. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85408. };
  85409. RayHelper.prototype.dispose = function () {
  85410. this.hide();
  85411. this.detachFromMesh();
  85412. this.ray = null;
  85413. };
  85414. return RayHelper;
  85415. }());
  85416. BABYLON.RayHelper = RayHelper;
  85417. })(BABYLON || (BABYLON = {}));
  85418. //# sourceMappingURL=babylon.rayHelper.js.map
  85419. var BABYLON;
  85420. (function (BABYLON) {
  85421. // load the inspector using require, if not present in the global namespace.
  85422. var DebugLayer = /** @class */ (function () {
  85423. function DebugLayer(scene) {
  85424. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85425. this._scene = scene;
  85426. // load inspector using require, if it doesn't exist on the global namespace.
  85427. }
  85428. /** Creates the inspector window. */
  85429. DebugLayer.prototype._createInspector = function (config) {
  85430. if (config === void 0) { config = {}; }
  85431. var popup = config.popup || false;
  85432. var initialTab = config.initialTab || 0;
  85433. var parentElement = config.parentElement || null;
  85434. if (!this._inspector) {
  85435. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85436. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85437. } // else nothing to do,; instance is already existing
  85438. };
  85439. DebugLayer.prototype.isVisible = function () {
  85440. if (!this._inspector) {
  85441. return false;
  85442. }
  85443. return true;
  85444. };
  85445. DebugLayer.prototype.hide = function () {
  85446. if (this._inspector) {
  85447. try {
  85448. this._inspector.dispose();
  85449. }
  85450. catch (e) {
  85451. // If the inspector has been removed directly from the inspector tool
  85452. }
  85453. this._inspector = null;
  85454. }
  85455. };
  85456. DebugLayer.prototype.show = function (config) {
  85457. if (config === void 0) { config = {}; }
  85458. if (typeof this.BJSINSPECTOR == 'undefined') {
  85459. // Load inspector and add it to the DOM
  85460. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85461. }
  85462. else {
  85463. // Otherwise creates the inspector
  85464. this._createInspector(config);
  85465. }
  85466. };
  85467. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85468. return DebugLayer;
  85469. }());
  85470. BABYLON.DebugLayer = DebugLayer;
  85471. })(BABYLON || (BABYLON = {}));
  85472. //# sourceMappingURL=babylon.debugLayer.js.map
  85473. var BABYLON;
  85474. (function (BABYLON) {
  85475. var Debug;
  85476. (function (Debug) {
  85477. /**
  85478. * Used to show the physics impostor around the specific mesh.
  85479. */
  85480. var PhysicsViewer = /** @class */ (function () {
  85481. function PhysicsViewer(scene) {
  85482. this._impostors = [];
  85483. this._meshes = [];
  85484. this._numMeshes = 0;
  85485. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85486. var physicEngine = this._scene.getPhysicsEngine();
  85487. if (physicEngine) {
  85488. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85489. }
  85490. }
  85491. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85492. var plugin = this._physicsEnginePlugin;
  85493. for (var i = 0; i < this._numMeshes; i++) {
  85494. var impostor = this._impostors[i];
  85495. if (!impostor) {
  85496. continue;
  85497. }
  85498. if (impostor.isDisposed) {
  85499. this.hideImpostor(this._impostors[i--]);
  85500. }
  85501. else {
  85502. var mesh = this._meshes[i];
  85503. if (mesh && plugin) {
  85504. plugin.syncMeshWithImpostor(mesh, impostor);
  85505. }
  85506. }
  85507. }
  85508. };
  85509. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85510. if (!this._scene) {
  85511. return;
  85512. }
  85513. for (var i = 0; i < this._numMeshes; i++) {
  85514. if (this._impostors[i] == impostor) {
  85515. return;
  85516. }
  85517. }
  85518. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85519. if (debugMesh) {
  85520. this._impostors[this._numMeshes] = impostor;
  85521. this._meshes[this._numMeshes] = debugMesh;
  85522. if (this._numMeshes === 0) {
  85523. this._renderFunction = this._updateDebugMeshes.bind(this);
  85524. this._scene.registerBeforeRender(this._renderFunction);
  85525. }
  85526. this._numMeshes++;
  85527. }
  85528. };
  85529. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85530. if (!impostor || !this._scene) {
  85531. return;
  85532. }
  85533. var removed = false;
  85534. for (var i = 0; i < this._numMeshes; i++) {
  85535. if (this._impostors[i] == impostor) {
  85536. var mesh = this._meshes[i];
  85537. if (!mesh) {
  85538. continue;
  85539. }
  85540. this._scene.removeMesh(mesh);
  85541. mesh.dispose();
  85542. this._numMeshes--;
  85543. if (this._numMeshes > 0) {
  85544. this._meshes[i] = this._meshes[this._numMeshes];
  85545. this._impostors[i] = this._impostors[this._numMeshes];
  85546. this._meshes[this._numMeshes] = null;
  85547. this._impostors[this._numMeshes] = null;
  85548. }
  85549. else {
  85550. this._meshes[0] = null;
  85551. this._impostors[0] = null;
  85552. }
  85553. removed = true;
  85554. break;
  85555. }
  85556. }
  85557. if (removed && this._numMeshes === 0) {
  85558. this._scene.unregisterBeforeRender(this._renderFunction);
  85559. }
  85560. };
  85561. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85562. if (!this._debugMaterial) {
  85563. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85564. this._debugMaterial.wireframe = true;
  85565. }
  85566. return this._debugMaterial;
  85567. };
  85568. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85569. if (!this._debugBoxMesh) {
  85570. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85571. this._debugBoxMesh.renderingGroupId = 1;
  85572. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85573. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85574. scene.removeMesh(this._debugBoxMesh);
  85575. }
  85576. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85577. };
  85578. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85579. if (!this._debugSphereMesh) {
  85580. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85581. this._debugSphereMesh.renderingGroupId = 1;
  85582. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85583. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85584. scene.removeMesh(this._debugSphereMesh);
  85585. }
  85586. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85587. };
  85588. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85589. var mesh = null;
  85590. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85591. mesh = this._getDebugBoxMesh(scene);
  85592. impostor.getBoxSizeToRef(mesh.scaling);
  85593. }
  85594. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85595. mesh = this._getDebugSphereMesh(scene);
  85596. var radius = impostor.getRadius();
  85597. mesh.scaling.x = radius * 2;
  85598. mesh.scaling.y = radius * 2;
  85599. mesh.scaling.z = radius * 2;
  85600. }
  85601. return mesh;
  85602. };
  85603. PhysicsViewer.prototype.dispose = function () {
  85604. for (var i = 0; i < this._numMeshes; i++) {
  85605. this.hideImpostor(this._impostors[i]);
  85606. }
  85607. if (this._debugBoxMesh) {
  85608. this._debugBoxMesh.dispose();
  85609. }
  85610. if (this._debugSphereMesh) {
  85611. this._debugSphereMesh.dispose();
  85612. }
  85613. if (this._debugMaterial) {
  85614. this._debugMaterial.dispose();
  85615. }
  85616. this._impostors.length = 0;
  85617. this._scene = null;
  85618. this._physicsEnginePlugin = null;
  85619. };
  85620. return PhysicsViewer;
  85621. }());
  85622. Debug.PhysicsViewer = PhysicsViewer;
  85623. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85624. })(BABYLON || (BABYLON = {}));
  85625. //# sourceMappingURL=babylon.physicsViewer.js.map
  85626. var BABYLON;
  85627. (function (BABYLON) {
  85628. var BoundingBoxRenderer = /** @class */ (function () {
  85629. function BoundingBoxRenderer(scene) {
  85630. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85631. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85632. this.showBackLines = true;
  85633. this.renderList = new BABYLON.SmartArray(32);
  85634. this._vertexBuffers = {};
  85635. this._scene = scene;
  85636. }
  85637. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85638. if (this._colorShader) {
  85639. return;
  85640. }
  85641. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85642. attributes: [BABYLON.VertexBuffer.PositionKind],
  85643. uniforms: ["world", "viewProjection", "color"]
  85644. });
  85645. var engine = this._scene.getEngine();
  85646. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85647. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85648. this._createIndexBuffer();
  85649. };
  85650. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85651. var engine = this._scene.getEngine();
  85652. 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]);
  85653. };
  85654. BoundingBoxRenderer.prototype._rebuild = function () {
  85655. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85656. if (vb) {
  85657. vb._rebuild();
  85658. }
  85659. this._createIndexBuffer();
  85660. };
  85661. BoundingBoxRenderer.prototype.reset = function () {
  85662. this.renderList.reset();
  85663. };
  85664. BoundingBoxRenderer.prototype.render = function () {
  85665. if (this.renderList.length === 0) {
  85666. return;
  85667. }
  85668. this._prepareRessources();
  85669. if (!this._colorShader.isReady()) {
  85670. return;
  85671. }
  85672. var engine = this._scene.getEngine();
  85673. engine.setDepthWrite(false);
  85674. this._colorShader._preBind();
  85675. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85676. var boundingBox = this.renderList.data[boundingBoxIndex];
  85677. var min = boundingBox.minimum;
  85678. var max = boundingBox.maximum;
  85679. var diff = max.subtract(min);
  85680. var median = min.add(diff.scale(0.5));
  85681. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85682. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85683. .multiply(boundingBox.getWorldMatrix());
  85684. // VBOs
  85685. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85686. if (this.showBackLines) {
  85687. // Back
  85688. engine.setDepthFunctionToGreaterOrEqual();
  85689. this._scene.resetCachedMaterial();
  85690. this._colorShader.setColor4("color", this.backColor.toColor4());
  85691. this._colorShader.bind(worldMatrix);
  85692. // Draw order
  85693. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85694. }
  85695. // Front
  85696. engine.setDepthFunctionToLess();
  85697. this._scene.resetCachedMaterial();
  85698. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85699. this._colorShader.bind(worldMatrix);
  85700. // Draw order
  85701. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85702. }
  85703. this._colorShader.unbind();
  85704. engine.setDepthFunctionToLessOrEqual();
  85705. engine.setDepthWrite(true);
  85706. };
  85707. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85708. this._prepareRessources();
  85709. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85710. return;
  85711. }
  85712. var engine = this._scene.getEngine();
  85713. engine.setDepthWrite(false);
  85714. engine.setColorWrite(false);
  85715. this._colorShader._preBind();
  85716. var boundingBox = mesh._boundingInfo.boundingBox;
  85717. var min = boundingBox.minimum;
  85718. var max = boundingBox.maximum;
  85719. var diff = max.subtract(min);
  85720. var median = min.add(diff.scale(0.5));
  85721. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85722. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85723. .multiply(boundingBox.getWorldMatrix());
  85724. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85725. engine.setDepthFunctionToLess();
  85726. this._scene.resetCachedMaterial();
  85727. this._colorShader.bind(worldMatrix);
  85728. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85729. this._colorShader.unbind();
  85730. engine.setDepthFunctionToLessOrEqual();
  85731. engine.setDepthWrite(true);
  85732. engine.setColorWrite(true);
  85733. };
  85734. BoundingBoxRenderer.prototype.dispose = function () {
  85735. if (!this._colorShader) {
  85736. return;
  85737. }
  85738. this.renderList.dispose();
  85739. this._colorShader.dispose();
  85740. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85741. if (buffer) {
  85742. buffer.dispose();
  85743. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85744. }
  85745. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85746. };
  85747. return BoundingBoxRenderer;
  85748. }());
  85749. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85750. })(BABYLON || (BABYLON = {}));
  85751. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85752. var BABYLON;
  85753. (function (BABYLON) {
  85754. /**
  85755. * Defines a target to use with MorphTargetManager
  85756. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85757. */
  85758. var MorphTarget = /** @class */ (function () {
  85759. /**
  85760. * Creates a new MorphTarget
  85761. * @param name defines the name of the target
  85762. * @param influence defines the influence to use
  85763. */
  85764. function MorphTarget(
  85765. /** defines the name of the target */
  85766. name, influence, scene) {
  85767. if (influence === void 0) { influence = 0; }
  85768. if (scene === void 0) { scene = null; }
  85769. this.name = name;
  85770. /**
  85771. * Gets or sets the list of animations
  85772. */
  85773. this.animations = new Array();
  85774. this._positions = null;
  85775. this._normals = null;
  85776. this._tangents = null;
  85777. /**
  85778. * Observable raised when the influence changes
  85779. */
  85780. this.onInfluenceChanged = new BABYLON.Observable();
  85781. this._animationPropertiesOverride = null;
  85782. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85783. this.influence = influence;
  85784. }
  85785. Object.defineProperty(MorphTarget.prototype, "influence", {
  85786. /**
  85787. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85788. */
  85789. get: function () {
  85790. return this._influence;
  85791. },
  85792. set: function (influence) {
  85793. if (this._influence === influence) {
  85794. return;
  85795. }
  85796. var previous = this._influence;
  85797. this._influence = influence;
  85798. if (this.onInfluenceChanged.hasObservers) {
  85799. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85800. }
  85801. },
  85802. enumerable: true,
  85803. configurable: true
  85804. });
  85805. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85806. /**
  85807. * Gets or sets the animation properties override
  85808. */
  85809. get: function () {
  85810. if (!this._animationPropertiesOverride && this._scene) {
  85811. return this._scene.animationPropertiesOverride;
  85812. }
  85813. return this._animationPropertiesOverride;
  85814. },
  85815. set: function (value) {
  85816. this._animationPropertiesOverride = value;
  85817. },
  85818. enumerable: true,
  85819. configurable: true
  85820. });
  85821. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85822. /**
  85823. * Gets a boolean defining if the target contains position data
  85824. */
  85825. get: function () {
  85826. return !!this._positions;
  85827. },
  85828. enumerable: true,
  85829. configurable: true
  85830. });
  85831. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85832. /**
  85833. * Gets a boolean defining if the target contains normal data
  85834. */
  85835. get: function () {
  85836. return !!this._normals;
  85837. },
  85838. enumerable: true,
  85839. configurable: true
  85840. });
  85841. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85842. /**
  85843. * Gets a boolean defining if the target contains tangent data
  85844. */
  85845. get: function () {
  85846. return !!this._tangents;
  85847. },
  85848. enumerable: true,
  85849. configurable: true
  85850. });
  85851. /**
  85852. * Affects position data to this target
  85853. * @param data defines the position data to use
  85854. */
  85855. MorphTarget.prototype.setPositions = function (data) {
  85856. this._positions = data;
  85857. };
  85858. /**
  85859. * Gets the position data stored in this target
  85860. * @returns a FloatArray containing the position data (or null if not present)
  85861. */
  85862. MorphTarget.prototype.getPositions = function () {
  85863. return this._positions;
  85864. };
  85865. /**
  85866. * Affects normal data to this target
  85867. * @param data defines the normal data to use
  85868. */
  85869. MorphTarget.prototype.setNormals = function (data) {
  85870. this._normals = data;
  85871. };
  85872. /**
  85873. * Gets the normal data stored in this target
  85874. * @returns a FloatArray containing the normal data (or null if not present)
  85875. */
  85876. MorphTarget.prototype.getNormals = function () {
  85877. return this._normals;
  85878. };
  85879. /**
  85880. * Affects tangent data to this target
  85881. * @param data defines the tangent data to use
  85882. */
  85883. MorphTarget.prototype.setTangents = function (data) {
  85884. this._tangents = data;
  85885. };
  85886. /**
  85887. * Gets the tangent data stored in this target
  85888. * @returns a FloatArray containing the tangent data (or null if not present)
  85889. */
  85890. MorphTarget.prototype.getTangents = function () {
  85891. return this._tangents;
  85892. };
  85893. /**
  85894. * Serializes the current target into a Serialization object
  85895. * @returns the serialized object
  85896. */
  85897. MorphTarget.prototype.serialize = function () {
  85898. var serializationObject = {};
  85899. serializationObject.name = this.name;
  85900. serializationObject.influence = this.influence;
  85901. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85902. if (this.hasNormals) {
  85903. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85904. }
  85905. if (this.hasTangents) {
  85906. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85907. }
  85908. // Animations
  85909. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85910. return serializationObject;
  85911. };
  85912. // Statics
  85913. /**
  85914. * Creates a new target from serialized data
  85915. * @param serializationObject defines the serialized data to use
  85916. * @returns a new MorphTarget
  85917. */
  85918. MorphTarget.Parse = function (serializationObject) {
  85919. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85920. result.setPositions(serializationObject.positions);
  85921. if (serializationObject.normals) {
  85922. result.setNormals(serializationObject.normals);
  85923. }
  85924. if (serializationObject.tangents) {
  85925. result.setTangents(serializationObject.tangents);
  85926. }
  85927. // Animations
  85928. if (serializationObject.animations) {
  85929. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85930. var parsedAnimation = serializationObject.animations[animationIndex];
  85931. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85932. }
  85933. }
  85934. return result;
  85935. };
  85936. /**
  85937. * Creates a MorphTarget from mesh data
  85938. * @param mesh defines the source mesh
  85939. * @param name defines the name to use for the new target
  85940. * @param influence defines the influence to attach to the target
  85941. * @returns a new MorphTarget
  85942. */
  85943. MorphTarget.FromMesh = function (mesh, name, influence) {
  85944. if (!name) {
  85945. name = mesh.name;
  85946. }
  85947. var result = new MorphTarget(name, influence, mesh.getScene());
  85948. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85950. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85951. }
  85952. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85953. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85954. }
  85955. return result;
  85956. };
  85957. return MorphTarget;
  85958. }());
  85959. BABYLON.MorphTarget = MorphTarget;
  85960. })(BABYLON || (BABYLON = {}));
  85961. //# sourceMappingURL=babylon.morphTarget.js.map
  85962. var BABYLON;
  85963. (function (BABYLON) {
  85964. /**
  85965. * This class is used to deform meshes using morphing between different targets
  85966. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85967. */
  85968. var MorphTargetManager = /** @class */ (function () {
  85969. /**
  85970. * Creates a new MorphTargetManager
  85971. * @param scene defines the current scene
  85972. */
  85973. function MorphTargetManager(scene) {
  85974. if (scene === void 0) { scene = null; }
  85975. this._targets = new Array();
  85976. this._targetObservable = new Array();
  85977. this._activeTargets = new BABYLON.SmartArray(16);
  85978. this._supportsNormals = false;
  85979. this._supportsTangents = false;
  85980. this._vertexCount = 0;
  85981. this._uniqueId = 0;
  85982. this._tempInfluences = new Array();
  85983. if (!scene) {
  85984. scene = BABYLON.Engine.LastCreatedScene;
  85985. }
  85986. this._scene = scene;
  85987. if (this._scene) {
  85988. this._scene.morphTargetManagers.push(this);
  85989. this._uniqueId = this._scene.getUniqueId();
  85990. }
  85991. }
  85992. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85993. /**
  85994. * Gets the unique ID of this manager
  85995. */
  85996. get: function () {
  85997. return this._uniqueId;
  85998. },
  85999. enumerable: true,
  86000. configurable: true
  86001. });
  86002. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86003. /**
  86004. * Gets the number of vertices handled by this manager
  86005. */
  86006. get: function () {
  86007. return this._vertexCount;
  86008. },
  86009. enumerable: true,
  86010. configurable: true
  86011. });
  86012. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86013. /**
  86014. * Gets a boolean indicating if this manager supports morphing of normals
  86015. */
  86016. get: function () {
  86017. return this._supportsNormals;
  86018. },
  86019. enumerable: true,
  86020. configurable: true
  86021. });
  86022. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86023. /**
  86024. * Gets a boolean indicating if this manager supports morphing of tangents
  86025. */
  86026. get: function () {
  86027. return this._supportsTangents;
  86028. },
  86029. enumerable: true,
  86030. configurable: true
  86031. });
  86032. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86033. /**
  86034. * Gets the number of targets stored in this manager
  86035. */
  86036. get: function () {
  86037. return this._targets.length;
  86038. },
  86039. enumerable: true,
  86040. configurable: true
  86041. });
  86042. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86043. /**
  86044. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86045. */
  86046. get: function () {
  86047. return this._activeTargets.length;
  86048. },
  86049. enumerable: true,
  86050. configurable: true
  86051. });
  86052. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86053. /**
  86054. * Gets the list of influences (one per target)
  86055. */
  86056. get: function () {
  86057. return this._influences;
  86058. },
  86059. enumerable: true,
  86060. configurable: true
  86061. });
  86062. /**
  86063. * Gets the active target at specified index. An active target is a target with an influence > 0
  86064. * @param index defines the index to check
  86065. * @returns the requested target
  86066. */
  86067. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86068. return this._activeTargets.data[index];
  86069. };
  86070. /**
  86071. * Gets the target at specified index
  86072. * @param index defines the index to check
  86073. * @returns the requested target
  86074. */
  86075. MorphTargetManager.prototype.getTarget = function (index) {
  86076. return this._targets[index];
  86077. };
  86078. /**
  86079. * Add a new target to this manager
  86080. * @param target defines the target to add
  86081. */
  86082. MorphTargetManager.prototype.addTarget = function (target) {
  86083. var _this = this;
  86084. this._targets.push(target);
  86085. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86086. _this._syncActiveTargets(needUpdate);
  86087. }));
  86088. this._syncActiveTargets(true);
  86089. };
  86090. /**
  86091. * Removes a target from the manager
  86092. * @param target defines the target to remove
  86093. */
  86094. MorphTargetManager.prototype.removeTarget = function (target) {
  86095. var index = this._targets.indexOf(target);
  86096. if (index >= 0) {
  86097. this._targets.splice(index, 1);
  86098. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86099. this._syncActiveTargets(true);
  86100. }
  86101. };
  86102. /**
  86103. * Serializes the current manager into a Serialization object
  86104. * @returns the serialized object
  86105. */
  86106. MorphTargetManager.prototype.serialize = function () {
  86107. var serializationObject = {};
  86108. serializationObject.id = this.uniqueId;
  86109. serializationObject.targets = [];
  86110. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86111. var target = _a[_i];
  86112. serializationObject.targets.push(target.serialize());
  86113. }
  86114. return serializationObject;
  86115. };
  86116. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86117. var influenceCount = 0;
  86118. this._activeTargets.reset();
  86119. this._supportsNormals = true;
  86120. this._supportsTangents = true;
  86121. this._vertexCount = 0;
  86122. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86123. var target = _a[_i];
  86124. this._activeTargets.push(target);
  86125. this._tempInfluences[influenceCount++] = target.influence;
  86126. var positions = target.getPositions();
  86127. if (positions) {
  86128. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86129. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86130. var vertexCount = positions.length / 3;
  86131. if (this._vertexCount === 0) {
  86132. this._vertexCount = vertexCount;
  86133. }
  86134. else if (this._vertexCount !== vertexCount) {
  86135. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86136. return;
  86137. }
  86138. }
  86139. }
  86140. if (!this._influences || this._influences.length !== influenceCount) {
  86141. this._influences = new Float32Array(influenceCount);
  86142. }
  86143. for (var index = 0; index < influenceCount; index++) {
  86144. this._influences[index] = this._tempInfluences[index];
  86145. }
  86146. if (needUpdate) {
  86147. this.synchronize();
  86148. }
  86149. };
  86150. /**
  86151. * Syncrhonize the targets with all the meshes using this morph target manager
  86152. */
  86153. MorphTargetManager.prototype.synchronize = function () {
  86154. if (!this._scene) {
  86155. return;
  86156. }
  86157. // Flag meshes as dirty to resync with the active targets
  86158. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86159. var mesh = _a[_i];
  86160. if (mesh.morphTargetManager === this) {
  86161. mesh._syncGeometryWithMorphTargetManager();
  86162. }
  86163. }
  86164. };
  86165. // Statics
  86166. /**
  86167. * Creates a new MorphTargetManager from serialized data
  86168. * @param serializationObject defines the serialized data
  86169. * @param scene defines the hosting scene
  86170. * @returns the new MorphTargetManager
  86171. */
  86172. MorphTargetManager.Parse = function (serializationObject, scene) {
  86173. var result = new MorphTargetManager(scene);
  86174. result._uniqueId = serializationObject.id;
  86175. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86176. var targetData = _a[_i];
  86177. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86178. }
  86179. return result;
  86180. };
  86181. return MorphTargetManager;
  86182. }());
  86183. BABYLON.MorphTargetManager = MorphTargetManager;
  86184. })(BABYLON || (BABYLON = {}));
  86185. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86186. var BABYLON;
  86187. (function (BABYLON) {
  86188. var Octree = /** @class */ (function () {
  86189. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86190. if (maxDepth === void 0) { maxDepth = 2; }
  86191. this.maxDepth = maxDepth;
  86192. this.dynamicContent = new Array();
  86193. this._maxBlockCapacity = maxBlockCapacity || 64;
  86194. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86195. this._creationFunc = creationFunc;
  86196. }
  86197. // Methods
  86198. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86199. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86200. };
  86201. Octree.prototype.addMesh = function (entry) {
  86202. for (var index = 0; index < this.blocks.length; index++) {
  86203. var block = this.blocks[index];
  86204. block.addEntry(entry);
  86205. }
  86206. };
  86207. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86208. this._selectionContent.reset();
  86209. for (var index = 0; index < this.blocks.length; index++) {
  86210. var block = this.blocks[index];
  86211. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86212. }
  86213. if (allowDuplicate) {
  86214. this._selectionContent.concat(this.dynamicContent);
  86215. }
  86216. else {
  86217. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86218. }
  86219. return this._selectionContent;
  86220. };
  86221. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86222. this._selectionContent.reset();
  86223. for (var index = 0; index < this.blocks.length; index++) {
  86224. var block = this.blocks[index];
  86225. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86226. }
  86227. if (allowDuplicate) {
  86228. this._selectionContent.concat(this.dynamicContent);
  86229. }
  86230. else {
  86231. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86232. }
  86233. return this._selectionContent;
  86234. };
  86235. Octree.prototype.intersectsRay = function (ray) {
  86236. this._selectionContent.reset();
  86237. for (var index = 0; index < this.blocks.length; index++) {
  86238. var block = this.blocks[index];
  86239. block.intersectsRay(ray, this._selectionContent);
  86240. }
  86241. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86242. return this._selectionContent;
  86243. };
  86244. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86245. target.blocks = new Array();
  86246. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86247. // Segmenting space
  86248. for (var x = 0; x < 2; x++) {
  86249. for (var y = 0; y < 2; y++) {
  86250. for (var z = 0; z < 2; z++) {
  86251. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86252. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86253. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86254. block.addEntries(entries);
  86255. target.blocks.push(block);
  86256. }
  86257. }
  86258. }
  86259. };
  86260. Octree.CreationFuncForMeshes = function (entry, block) {
  86261. var boundingInfo = entry.getBoundingInfo();
  86262. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86263. block.entries.push(entry);
  86264. }
  86265. };
  86266. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86267. var boundingInfo = entry.getBoundingInfo();
  86268. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86269. block.entries.push(entry);
  86270. }
  86271. };
  86272. return Octree;
  86273. }());
  86274. BABYLON.Octree = Octree;
  86275. })(BABYLON || (BABYLON = {}));
  86276. //# sourceMappingURL=babylon.octree.js.map
  86277. var BABYLON;
  86278. (function (BABYLON) {
  86279. var OctreeBlock = /** @class */ (function () {
  86280. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86281. this.entries = new Array();
  86282. this._boundingVectors = new Array();
  86283. this._capacity = capacity;
  86284. this._depth = depth;
  86285. this._maxDepth = maxDepth;
  86286. this._creationFunc = creationFunc;
  86287. this._minPoint = minPoint;
  86288. this._maxPoint = maxPoint;
  86289. this._boundingVectors.push(minPoint.clone());
  86290. this._boundingVectors.push(maxPoint.clone());
  86291. this._boundingVectors.push(minPoint.clone());
  86292. this._boundingVectors[2].x = maxPoint.x;
  86293. this._boundingVectors.push(minPoint.clone());
  86294. this._boundingVectors[3].y = maxPoint.y;
  86295. this._boundingVectors.push(minPoint.clone());
  86296. this._boundingVectors[4].z = maxPoint.z;
  86297. this._boundingVectors.push(maxPoint.clone());
  86298. this._boundingVectors[5].z = minPoint.z;
  86299. this._boundingVectors.push(maxPoint.clone());
  86300. this._boundingVectors[6].x = minPoint.x;
  86301. this._boundingVectors.push(maxPoint.clone());
  86302. this._boundingVectors[7].y = minPoint.y;
  86303. }
  86304. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86305. // Property
  86306. get: function () {
  86307. return this._capacity;
  86308. },
  86309. enumerable: true,
  86310. configurable: true
  86311. });
  86312. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86313. get: function () {
  86314. return this._minPoint;
  86315. },
  86316. enumerable: true,
  86317. configurable: true
  86318. });
  86319. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86320. get: function () {
  86321. return this._maxPoint;
  86322. },
  86323. enumerable: true,
  86324. configurable: true
  86325. });
  86326. // Methods
  86327. OctreeBlock.prototype.addEntry = function (entry) {
  86328. if (this.blocks) {
  86329. for (var index = 0; index < this.blocks.length; index++) {
  86330. var block = this.blocks[index];
  86331. block.addEntry(entry);
  86332. }
  86333. return;
  86334. }
  86335. this._creationFunc(entry, this);
  86336. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86337. this.createInnerBlocks();
  86338. }
  86339. };
  86340. OctreeBlock.prototype.addEntries = function (entries) {
  86341. for (var index = 0; index < entries.length; index++) {
  86342. var mesh = entries[index];
  86343. this.addEntry(mesh);
  86344. }
  86345. };
  86346. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86347. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86348. if (this.blocks) {
  86349. for (var index = 0; index < this.blocks.length; index++) {
  86350. var block = this.blocks[index];
  86351. block.select(frustumPlanes, selection, allowDuplicate);
  86352. }
  86353. return;
  86354. }
  86355. if (allowDuplicate) {
  86356. selection.concat(this.entries);
  86357. }
  86358. else {
  86359. selection.concatWithNoDuplicate(this.entries);
  86360. }
  86361. }
  86362. };
  86363. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86364. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86365. if (this.blocks) {
  86366. for (var index = 0; index < this.blocks.length; index++) {
  86367. var block = this.blocks[index];
  86368. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86369. }
  86370. return;
  86371. }
  86372. if (allowDuplicate) {
  86373. selection.concat(this.entries);
  86374. }
  86375. else {
  86376. selection.concatWithNoDuplicate(this.entries);
  86377. }
  86378. }
  86379. };
  86380. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86381. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86382. if (this.blocks) {
  86383. for (var index = 0; index < this.blocks.length; index++) {
  86384. var block = this.blocks[index];
  86385. block.intersectsRay(ray, selection);
  86386. }
  86387. return;
  86388. }
  86389. selection.concatWithNoDuplicate(this.entries);
  86390. }
  86391. };
  86392. OctreeBlock.prototype.createInnerBlocks = function () {
  86393. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86394. };
  86395. return OctreeBlock;
  86396. }());
  86397. BABYLON.OctreeBlock = OctreeBlock;
  86398. })(BABYLON || (BABYLON = {}));
  86399. //# sourceMappingURL=babylon.octreeBlock.js.map
  86400. var BABYLON;
  86401. (function (BABYLON) {
  86402. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86403. __extends(VRDistortionCorrectionPostProcess, _super);
  86404. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86405. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86406. 'LensCenter',
  86407. 'Scale',
  86408. 'ScaleIn',
  86409. 'HmdWarpParam'
  86410. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86411. _this._isRightEye = isRightEye;
  86412. _this._distortionFactors = vrMetrics.distortionK;
  86413. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86414. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86415. _this.adaptScaleToCurrentViewport = true;
  86416. _this.onSizeChangedObservable.add(function () {
  86417. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86418. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86419. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86420. });
  86421. _this.onApplyObservable.add(function (effect) {
  86422. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86423. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86424. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86425. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86426. });
  86427. return _this;
  86428. }
  86429. return VRDistortionCorrectionPostProcess;
  86430. }(BABYLON.PostProcess));
  86431. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86432. })(BABYLON || (BABYLON = {}));
  86433. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86434. var BABYLON;
  86435. (function (BABYLON) {
  86436. /**
  86437. * Postprocess used to generate anaglyphic rendering
  86438. */
  86439. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86440. __extends(AnaglyphPostProcess, _super);
  86441. /**
  86442. * Creates a new AnaglyphPostProcess
  86443. * @param name defines postprocess name
  86444. * @param options defines creation options or target ratio scale
  86445. * @param rigCameras defines cameras using this postprocess
  86446. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86447. * @param engine defines hosting engine
  86448. * @param reusable defines if the postprocess will be reused multiple times per frame
  86449. */
  86450. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86451. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86452. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86453. _this.onApplyObservable.add(function (effect) {
  86454. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86455. });
  86456. return _this;
  86457. }
  86458. return AnaglyphPostProcess;
  86459. }(BABYLON.PostProcess));
  86460. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86461. })(BABYLON || (BABYLON = {}));
  86462. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86463. var BABYLON;
  86464. (function (BABYLON) {
  86465. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86466. __extends(StereoscopicInterlacePostProcess, _super);
  86467. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86468. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86469. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86470. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86471. _this.onSizeChangedObservable.add(function () {
  86472. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86473. });
  86474. _this.onApplyObservable.add(function (effect) {
  86475. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86476. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86477. });
  86478. return _this;
  86479. }
  86480. return StereoscopicInterlacePostProcess;
  86481. }(BABYLON.PostProcess));
  86482. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86483. })(BABYLON || (BABYLON = {}));
  86484. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86485. var BABYLON;
  86486. (function (BABYLON) {
  86487. /**
  86488. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86489. * Screen rotation is taken into account.
  86490. */
  86491. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86492. function FreeCameraDeviceOrientationInput() {
  86493. var _this = this;
  86494. this._screenOrientationAngle = 0;
  86495. this._screenQuaternion = new BABYLON.Quaternion();
  86496. this._alpha = 0;
  86497. this._beta = 0;
  86498. this._gamma = 0;
  86499. this._orientationChanged = function () {
  86500. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86501. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86502. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86503. };
  86504. this._deviceOrientation = function (evt) {
  86505. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86506. _this._beta = evt.beta !== null ? evt.beta : 0;
  86507. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86508. };
  86509. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86510. this._orientationChanged();
  86511. }
  86512. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86513. get: function () {
  86514. return this._camera;
  86515. },
  86516. set: function (camera) {
  86517. this._camera = camera;
  86518. if (this._camera != null && !this._camera.rotationQuaternion) {
  86519. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86520. }
  86521. },
  86522. enumerable: true,
  86523. configurable: true
  86524. });
  86525. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86526. window.addEventListener("orientationchange", this._orientationChanged);
  86527. window.addEventListener("deviceorientation", this._deviceOrientation);
  86528. //In certain cases, the attach control is called AFTER orientation was changed,
  86529. //So this is needed.
  86530. this._orientationChanged();
  86531. };
  86532. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86533. window.removeEventListener("orientationchange", this._orientationChanged);
  86534. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86535. };
  86536. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86537. //if no device orientation provided, don't update the rotation.
  86538. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86539. if (!this._alpha)
  86540. return;
  86541. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86542. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86543. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86544. //Mirror on XY Plane
  86545. this._camera.rotationQuaternion.z *= -1;
  86546. this._camera.rotationQuaternion.w *= -1;
  86547. };
  86548. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86549. return "FreeCameraDeviceOrientationInput";
  86550. };
  86551. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86552. return "deviceOrientation";
  86553. };
  86554. return FreeCameraDeviceOrientationInput;
  86555. }());
  86556. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86557. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86558. })(BABYLON || (BABYLON = {}));
  86559. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86560. var BABYLON;
  86561. (function (BABYLON) {
  86562. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86563. function ArcRotateCameraVRDeviceOrientationInput() {
  86564. this.alphaCorrection = 1;
  86565. this.betaCorrection = 1;
  86566. this.gammaCorrection = 1;
  86567. this._alpha = 0;
  86568. this._gamma = 0;
  86569. this._dirty = false;
  86570. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86571. }
  86572. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86573. this.camera.attachControl(element, noPreventDefault);
  86574. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86575. };
  86576. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86577. if (evt.alpha !== null) {
  86578. this._alpha = +evt.alpha | 0;
  86579. }
  86580. if (evt.gamma !== null) {
  86581. this._gamma = +evt.gamma | 0;
  86582. }
  86583. this._dirty = true;
  86584. };
  86585. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86586. if (this._dirty) {
  86587. this._dirty = false;
  86588. if (this._gamma < 0) {
  86589. this._gamma = 180 + this._gamma;
  86590. }
  86591. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86592. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86593. }
  86594. };
  86595. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86596. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86597. };
  86598. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86599. return "ArcRotateCameraVRDeviceOrientationInput";
  86600. };
  86601. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86602. return "VRDeviceOrientation";
  86603. };
  86604. return ArcRotateCameraVRDeviceOrientationInput;
  86605. }());
  86606. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86607. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86608. })(BABYLON || (BABYLON = {}));
  86609. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86610. var BABYLON;
  86611. (function (BABYLON) {
  86612. var VRCameraMetrics = /** @class */ (function () {
  86613. function VRCameraMetrics() {
  86614. this.compensateDistortion = true;
  86615. }
  86616. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86617. get: function () {
  86618. return this.hResolution / (2 * this.vResolution);
  86619. },
  86620. enumerable: true,
  86621. configurable: true
  86622. });
  86623. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86624. get: function () {
  86625. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86626. },
  86627. enumerable: true,
  86628. configurable: true
  86629. });
  86630. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86631. get: function () {
  86632. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86633. var h = (4 * meters) / this.hScreenSize;
  86634. return BABYLON.Matrix.Translation(h, 0, 0);
  86635. },
  86636. enumerable: true,
  86637. configurable: true
  86638. });
  86639. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86640. get: function () {
  86641. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86642. var h = (4 * meters) / this.hScreenSize;
  86643. return BABYLON.Matrix.Translation(-h, 0, 0);
  86644. },
  86645. enumerable: true,
  86646. configurable: true
  86647. });
  86648. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86649. get: function () {
  86650. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86651. },
  86652. enumerable: true,
  86653. configurable: true
  86654. });
  86655. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86656. get: function () {
  86657. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86658. },
  86659. enumerable: true,
  86660. configurable: true
  86661. });
  86662. VRCameraMetrics.GetDefault = function () {
  86663. var result = new VRCameraMetrics();
  86664. result.hResolution = 1280;
  86665. result.vResolution = 800;
  86666. result.hScreenSize = 0.149759993;
  86667. result.vScreenSize = 0.0935999975;
  86668. result.vScreenCenter = 0.0467999987;
  86669. result.eyeToScreenDistance = 0.0410000011;
  86670. result.lensSeparationDistance = 0.0635000020;
  86671. result.interpupillaryDistance = 0.0640000030;
  86672. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86673. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86674. result.postProcessScaleFactor = 1.714605507808412;
  86675. result.lensCenterOffset = 0.151976421;
  86676. return result;
  86677. };
  86678. return VRCameraMetrics;
  86679. }());
  86680. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86681. })(BABYLON || (BABYLON = {}));
  86682. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86683. var BABYLON;
  86684. (function (BABYLON) {
  86685. /**
  86686. * This represents a WebVR camera.
  86687. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86688. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86689. */
  86690. var WebVRFreeCamera = /** @class */ (function (_super) {
  86691. __extends(WebVRFreeCamera, _super);
  86692. /**
  86693. * Instantiates a WebVRFreeCamera.
  86694. * @param name The name of the WebVRFreeCamera
  86695. * @param position The starting anchor position for the camera
  86696. * @param scene The scene the camera belongs to
  86697. * @param webVROptions a set of customizable options for the webVRCamera
  86698. */
  86699. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86700. if (webVROptions === void 0) { webVROptions = {}; }
  86701. var _this = _super.call(this, name, position, scene) || this;
  86702. _this.webVROptions = webVROptions;
  86703. /**
  86704. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86705. */
  86706. _this._vrDevice = null;
  86707. /**
  86708. * The rawPose of the vrDevice.
  86709. */
  86710. _this.rawPose = null;
  86711. _this._specsVersion = "1.1";
  86712. _this._attached = false;
  86713. _this._descendants = [];
  86714. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86715. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86716. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86717. _this._standingMatrix = null;
  86718. /**
  86719. * Represents device position in babylon space.
  86720. */
  86721. _this.devicePosition = BABYLON.Vector3.Zero();
  86722. /**
  86723. * Represents device rotation in babylon space.
  86724. */
  86725. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86726. /**
  86727. * The scale of the device to be used when translating from device space to babylon space.
  86728. */
  86729. _this.deviceScaleFactor = 1;
  86730. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86731. _this._worldToDevice = BABYLON.Matrix.Identity();
  86732. /**
  86733. * References to the webVR controllers for the vrDevice.
  86734. */
  86735. _this.controllers = [];
  86736. /**
  86737. * Emits an event when a controller is attached.
  86738. */
  86739. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86740. /**
  86741. * Emits an event when a controller's mesh has been loaded;
  86742. */
  86743. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86744. /**
  86745. * If the rig cameras be used as parent instead of this camera.
  86746. */
  86747. _this.rigParenting = true;
  86748. _this._defaultHeight = undefined;
  86749. _this._workingVector = BABYLON.Vector3.Zero();
  86750. _this._oneVector = BABYLON.Vector3.One();
  86751. _this._workingMatrix = BABYLON.Matrix.Identity();
  86752. _this._cache.position = BABYLON.Vector3.Zero();
  86753. if (webVROptions.defaultHeight) {
  86754. _this._defaultHeight = webVROptions.defaultHeight;
  86755. _this.position.y = _this._defaultHeight;
  86756. }
  86757. _this.minZ = 0.1;
  86758. //legacy support - the compensation boolean was removed.
  86759. if (arguments.length === 5) {
  86760. _this.webVROptions = arguments[4];
  86761. }
  86762. // default webVR options
  86763. if (_this.webVROptions.trackPosition == undefined) {
  86764. _this.webVROptions.trackPosition = true;
  86765. }
  86766. if (_this.webVROptions.controllerMeshes == undefined) {
  86767. _this.webVROptions.controllerMeshes = true;
  86768. }
  86769. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86770. _this.webVROptions.defaultLightingOnControllers = true;
  86771. }
  86772. _this.rotationQuaternion = new BABYLON.Quaternion();
  86773. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86774. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86775. }
  86776. //enable VR
  86777. var engine = _this.getEngine();
  86778. _this._onVREnabled = function (success) { if (success) {
  86779. _this.initControllers();
  86780. } };
  86781. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86782. engine.initWebVR().add(function (event) {
  86783. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86784. return;
  86785. }
  86786. _this._vrDevice = event.vrDisplay;
  86787. //reset the rig parameters.
  86788. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86789. if (_this._attached) {
  86790. _this.getEngine().enableVR();
  86791. }
  86792. });
  86793. if (typeof (VRFrameData) !== "undefined")
  86794. _this._frameData = new VRFrameData();
  86795. /**
  86796. * The idea behind the following lines:
  86797. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86798. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86799. * the second will not show it correctly.
  86800. *
  86801. * To solve this - each object that has the camera as parent will be added to a protected array.
  86802. * When the rig camera renders, it will take this array and set all of those to be its children.
  86803. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86804. * Amazing!
  86805. */
  86806. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86807. if (camera.parent === _this && _this.rigParenting) {
  86808. _this._descendants = _this.getDescendants(true, function (n) {
  86809. // don't take the cameras or the controllers!
  86810. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86811. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86812. return !isController && !isRigCamera;
  86813. });
  86814. _this._descendants.forEach(function (node) {
  86815. node.parent = camera;
  86816. });
  86817. }
  86818. });
  86819. scene.onAfterCameraRenderObservable.add(function (camera) {
  86820. if (camera.parent === _this && _this.rigParenting) {
  86821. _this._descendants.forEach(function (node) {
  86822. node.parent = _this;
  86823. });
  86824. }
  86825. });
  86826. return _this;
  86827. }
  86828. /**
  86829. * Gets the device distance from the ground in meters.
  86830. * @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.
  86831. */
  86832. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86833. if (this._standingMatrix) {
  86834. // Add standing matrix offset to get real offset from ground in room
  86835. this._standingMatrix.getTranslationToRef(this._workingVector);
  86836. return this._deviceRoomPosition.y + this._workingVector.y;
  86837. }
  86838. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86839. return this._defaultHeight || 0;
  86840. };
  86841. /**
  86842. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86843. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86844. */
  86845. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86846. var _this = this;
  86847. if (callback === void 0) { callback = function (bool) { }; }
  86848. // Use standing matrix if available
  86849. this.getEngine().initWebVRAsync().then(function (result) {
  86850. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86851. callback(false);
  86852. }
  86853. else {
  86854. _this._standingMatrix = new BABYLON.Matrix();
  86855. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86856. if (!_this.getScene().useRightHandedSystem) {
  86857. [2, 6, 8, 9, 14].forEach(function (num) {
  86858. if (_this._standingMatrix) {
  86859. _this._standingMatrix.m[num] *= -1;
  86860. }
  86861. });
  86862. }
  86863. callback(true);
  86864. }
  86865. });
  86866. };
  86867. /**
  86868. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86869. * @returns A promise with a boolean set to if the standing matrix is supported.
  86870. */
  86871. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86872. var _this = this;
  86873. return new Promise(function (res, rej) {
  86874. _this.useStandingMatrix(function (supported) {
  86875. res(supported);
  86876. });
  86877. });
  86878. };
  86879. /**
  86880. * Disposes the camera
  86881. */
  86882. WebVRFreeCamera.prototype.dispose = function () {
  86883. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86884. _super.prototype.dispose.call(this);
  86885. };
  86886. /**
  86887. * Gets a vrController by name.
  86888. * @param name The name of the controller to retreive
  86889. * @returns the controller matching the name specified or null if not found
  86890. */
  86891. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86892. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86893. var gp = _a[_i];
  86894. if (gp.hand === name) {
  86895. return gp;
  86896. }
  86897. }
  86898. return null;
  86899. };
  86900. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86901. /**
  86902. * The controller corrisponding to the users left hand.
  86903. */
  86904. get: function () {
  86905. if (!this._leftController) {
  86906. this._leftController = this.getControllerByName("left");
  86907. }
  86908. return this._leftController;
  86909. },
  86910. enumerable: true,
  86911. configurable: true
  86912. });
  86913. ;
  86914. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86915. /**
  86916. * The controller corrisponding to the users right hand.
  86917. */
  86918. get: function () {
  86919. if (!this._rightController) {
  86920. this._rightController = this.getControllerByName("right");
  86921. }
  86922. return this._rightController;
  86923. },
  86924. enumerable: true,
  86925. configurable: true
  86926. });
  86927. ;
  86928. /**
  86929. * Casts a ray forward from the vrCamera's gaze.
  86930. * @param length Length of the ray (default: 100)
  86931. * @returns the ray corrisponding to the gaze
  86932. */
  86933. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86934. if (length === void 0) { length = 100; }
  86935. if (this.leftCamera) {
  86936. // Use left eye to avoid computation to compute center on every call
  86937. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86938. }
  86939. else {
  86940. return _super.prototype.getForwardRay.call(this, length);
  86941. }
  86942. };
  86943. /**
  86944. * Updates the camera based on device's frame data
  86945. */
  86946. WebVRFreeCamera.prototype._checkInputs = function () {
  86947. if (this._vrDevice && this._vrDevice.isPresenting) {
  86948. this._vrDevice.getFrameData(this._frameData);
  86949. this.updateFromDevice(this._frameData.pose);
  86950. }
  86951. _super.prototype._checkInputs.call(this);
  86952. };
  86953. /**
  86954. * Updates the poseControlled values based on the input device pose.
  86955. * @param poseData Pose coming from the device
  86956. */
  86957. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86958. if (poseData && poseData.orientation) {
  86959. this.rawPose = poseData;
  86960. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86961. if (this.getScene().useRightHandedSystem) {
  86962. this._deviceRoomRotationQuaternion.z *= -1;
  86963. this._deviceRoomRotationQuaternion.w *= -1;
  86964. }
  86965. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86966. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86967. if (this.getScene().useRightHandedSystem) {
  86968. this._deviceRoomPosition.z *= -1;
  86969. }
  86970. }
  86971. }
  86972. };
  86973. /**
  86974. * WebVR's attach control will start broadcasting frames to the device.
  86975. * Note that in certain browsers (chrome for example) this function must be called
  86976. * within a user-interaction callback. Example:
  86977. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86978. *
  86979. * @param element html element to attach the vrDevice to
  86980. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86981. */
  86982. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86983. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86984. this._attached = true;
  86985. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86986. if (this._vrDevice) {
  86987. this.getEngine().enableVR();
  86988. }
  86989. };
  86990. /**
  86991. * Detaches the camera from the html element and disables VR
  86992. *
  86993. * @param element html element to detach from
  86994. */
  86995. WebVRFreeCamera.prototype.detachControl = function (element) {
  86996. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86997. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86998. _super.prototype.detachControl.call(this, element);
  86999. this._attached = false;
  87000. this.getEngine().disableVR();
  87001. };
  87002. /**
  87003. * @returns the name of this class
  87004. */
  87005. WebVRFreeCamera.prototype.getClassName = function () {
  87006. return "WebVRFreeCamera";
  87007. };
  87008. /**
  87009. * Calls resetPose on the vrDisplay
  87010. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87011. */
  87012. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87013. //uses the vrDisplay's "resetPose()".
  87014. //pitch and roll won't be affected.
  87015. this._vrDevice.resetPose();
  87016. };
  87017. /**
  87018. * Updates the rig cameras (left and right eye)
  87019. */
  87020. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87021. var camLeft = this._rigCameras[0];
  87022. var camRight = this._rigCameras[1];
  87023. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87024. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87025. camLeft.position.copyFrom(this._deviceRoomPosition);
  87026. camRight.position.copyFrom(this._deviceRoomPosition);
  87027. };
  87028. /**
  87029. * Updates the cached values of the camera
  87030. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87031. */
  87032. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87033. var _this = this;
  87034. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87035. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87036. if (!this.updateCacheCalled) {
  87037. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87038. this.updateCacheCalled = true;
  87039. this.update();
  87040. }
  87041. // Set working vector to the device position in room space rotated by the new rotation
  87042. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87043. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87044. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87045. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87046. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87047. // Add translation from anchor position
  87048. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87049. this._workingVector.addInPlace(this.position);
  87050. this._workingVector.subtractInPlace(this._cache.position);
  87051. this._deviceToWorld.setTranslation(this._workingVector);
  87052. // Set an inverted matrix to be used when updating the camera
  87053. this._deviceToWorld.invertToRef(this._worldToDevice);
  87054. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87055. this.controllers.forEach(function (controller) {
  87056. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87057. controller.update();
  87058. });
  87059. }
  87060. if (!ignoreParentClass) {
  87061. _super.prototype._updateCache.call(this);
  87062. }
  87063. this.updateCacheCalled = false;
  87064. };
  87065. /**
  87066. * Updates the current device position and rotation in the babylon world
  87067. */
  87068. WebVRFreeCamera.prototype.update = function () {
  87069. // Get current device position in babylon world
  87070. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87071. // Get current device rotation in babylon world
  87072. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87073. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87074. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87075. _super.prototype.update.call(this);
  87076. };
  87077. /**
  87078. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87079. * @returns an identity matrix
  87080. */
  87081. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87082. return BABYLON.Matrix.Identity();
  87083. };
  87084. /**
  87085. * This function is called by the two RIG cameras.
  87086. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87087. */
  87088. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87089. var _this = this;
  87090. // Update the parent camera prior to using a child camera to avoid desynchronization
  87091. var parentCamera = this._cameraRigParams["parentCamera"];
  87092. parentCamera._updateCache();
  87093. //WebVR 1.1
  87094. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87095. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87096. if (!this.getScene().useRightHandedSystem) {
  87097. [2, 6, 8, 9, 14].forEach(function (num) {
  87098. _this._webvrViewMatrix.m[num] *= -1;
  87099. });
  87100. }
  87101. // update the camera rotation matrix
  87102. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87103. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87104. // Computing target and final matrix
  87105. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87106. // should the view matrix be updated with scale and position offset?
  87107. if (parentCamera.deviceScaleFactor !== 1) {
  87108. this._webvrViewMatrix.invert();
  87109. // scale the position, if set
  87110. if (parentCamera.deviceScaleFactor) {
  87111. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87112. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87113. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87114. }
  87115. this._webvrViewMatrix.invert();
  87116. }
  87117. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87118. // Compute global position
  87119. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87120. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87121. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87122. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87123. this._markSyncedWithParent();
  87124. return this._webvrViewMatrix;
  87125. };
  87126. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87127. var _this = this;
  87128. var parentCamera = this.parent;
  87129. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87130. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87131. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87132. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87133. //babylon compatible matrix
  87134. if (!this.getScene().useRightHandedSystem) {
  87135. [8, 9, 10, 11].forEach(function (num) {
  87136. _this._projectionMatrix.m[num] *= -1;
  87137. });
  87138. }
  87139. return this._projectionMatrix;
  87140. };
  87141. /**
  87142. * Initializes the controllers and their meshes
  87143. */
  87144. WebVRFreeCamera.prototype.initControllers = function () {
  87145. var _this = this;
  87146. this.controllers = [];
  87147. var manager = this.getScene().gamepadManager;
  87148. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87149. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87150. var webVrController = gamepad;
  87151. if (webVrController.defaultModel) {
  87152. webVrController.defaultModel.setEnabled(false);
  87153. }
  87154. if (webVrController.hand === "right") {
  87155. _this._rightController = null;
  87156. }
  87157. if (webVrController.hand === "left") {
  87158. _this._leftController = null;
  87159. }
  87160. var controllerIndex = _this.controllers.indexOf(webVrController);
  87161. if (controllerIndex !== -1) {
  87162. _this.controllers.splice(controllerIndex, 1);
  87163. }
  87164. }
  87165. });
  87166. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87167. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87168. var webVrController_1 = gamepad;
  87169. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87170. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87171. if (_this.webVROptions.controllerMeshes) {
  87172. if (webVrController_1.defaultModel) {
  87173. webVrController_1.defaultModel.setEnabled(true);
  87174. }
  87175. else {
  87176. // Load the meshes
  87177. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87178. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87179. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87180. if (_this.webVROptions.defaultLightingOnControllers) {
  87181. if (!_this._lightOnControllers) {
  87182. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87183. }
  87184. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87185. var children = mesh.getChildren();
  87186. if (children.length !== 0) {
  87187. children.forEach(function (mesh) {
  87188. light.includedOnlyMeshes.push(mesh);
  87189. activateLightOnSubMeshes_1(mesh, light);
  87190. });
  87191. }
  87192. };
  87193. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87194. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87195. }
  87196. });
  87197. }
  87198. }
  87199. webVrController_1.attachToPoseControlledCamera(_this);
  87200. // since this is async - sanity check. Is the controller already stored?
  87201. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87202. //add to the controllers array
  87203. _this.controllers.push(webVrController_1);
  87204. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87205. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87206. // So we're overriding setting left & right manually to be sure
  87207. var firstViveWandDetected = false;
  87208. for (var i = 0; i < _this.controllers.length; i++) {
  87209. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87210. if (!firstViveWandDetected) {
  87211. firstViveWandDetected = true;
  87212. _this.controllers[i].hand = "left";
  87213. }
  87214. else {
  87215. _this.controllers[i].hand = "right";
  87216. }
  87217. }
  87218. }
  87219. //did we find enough controllers? Great! let the developer know.
  87220. if (_this.controllers.length >= 2) {
  87221. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87222. }
  87223. }
  87224. }
  87225. });
  87226. };
  87227. return WebVRFreeCamera;
  87228. }(BABYLON.FreeCamera));
  87229. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87230. })(BABYLON || (BABYLON = {}));
  87231. //# sourceMappingURL=babylon.webVRCamera.js.map
  87232. var BABYLON;
  87233. (function (BABYLON) {
  87234. // We're mainly based on the logic defined into the FreeCamera code
  87235. /**
  87236. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87237. * being tilted forward or back and left or right.
  87238. */
  87239. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87240. __extends(DeviceOrientationCamera, _super);
  87241. /**
  87242. * Creates a new device orientation camera
  87243. * @param name The name of the camera
  87244. * @param position The start position camera
  87245. * @param scene The scene the camera belongs to
  87246. */
  87247. function DeviceOrientationCamera(name, position, scene) {
  87248. var _this = _super.call(this, name, position, scene) || this;
  87249. _this._quaternionCache = new BABYLON.Quaternion();
  87250. _this.inputs.addDeviceOrientation();
  87251. return _this;
  87252. }
  87253. /**
  87254. * Gets the current instance class name ("DeviceOrientationCamera").
  87255. * This helps avoiding instanceof at run time.
  87256. * @returns the class name
  87257. */
  87258. DeviceOrientationCamera.prototype.getClassName = function () {
  87259. return "DeviceOrientationCamera";
  87260. };
  87261. /**
  87262. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87263. */
  87264. DeviceOrientationCamera.prototype._checkInputs = function () {
  87265. _super.prototype._checkInputs.call(this);
  87266. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87267. if (this._initialQuaternion) {
  87268. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87269. }
  87270. };
  87271. /**
  87272. * Reset the camera to its default orientation on the specified axis only.
  87273. * @param axis The axis to reset
  87274. */
  87275. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87276. var _this = this;
  87277. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87278. //can only work if this camera has a rotation quaternion already.
  87279. if (!this.rotationQuaternion)
  87280. return;
  87281. if (!this._initialQuaternion) {
  87282. this._initialQuaternion = new BABYLON.Quaternion();
  87283. }
  87284. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87285. ['x', 'y', 'z'].forEach(function (axisName) {
  87286. if (!axis[axisName]) {
  87287. _this._initialQuaternion[axisName] = 0;
  87288. }
  87289. else {
  87290. _this._initialQuaternion[axisName] *= -1;
  87291. }
  87292. });
  87293. this._initialQuaternion.normalize();
  87294. //force rotation update
  87295. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87296. };
  87297. return DeviceOrientationCamera;
  87298. }(BABYLON.FreeCamera));
  87299. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87300. })(BABYLON || (BABYLON = {}));
  87301. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87302. var BABYLON;
  87303. (function (BABYLON) {
  87304. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87305. __extends(VRDeviceOrientationFreeCamera, _super);
  87306. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87307. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87308. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87309. var _this = _super.call(this, name, position, scene) || this;
  87310. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87311. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87312. return _this;
  87313. }
  87314. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87315. return "VRDeviceOrientationFreeCamera";
  87316. };
  87317. return VRDeviceOrientationFreeCamera;
  87318. }(BABYLON.DeviceOrientationCamera));
  87319. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87320. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87321. __extends(VRDeviceOrientationGamepadCamera, _super);
  87322. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87323. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87324. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87325. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87326. _this.inputs.addGamepad();
  87327. return _this;
  87328. }
  87329. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87330. return "VRDeviceOrientationGamepadCamera";
  87331. };
  87332. return VRDeviceOrientationGamepadCamera;
  87333. }(VRDeviceOrientationFreeCamera));
  87334. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87335. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87336. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87337. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87338. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87339. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87340. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87341. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87342. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87343. _this.inputs.addVRDeviceOrientation();
  87344. return _this;
  87345. }
  87346. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87347. return "VRDeviceOrientationArcRotateCamera";
  87348. };
  87349. return VRDeviceOrientationArcRotateCamera;
  87350. }(BABYLON.ArcRotateCamera));
  87351. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87352. })(BABYLON || (BABYLON = {}));
  87353. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87354. var BABYLON;
  87355. (function (BABYLON) {
  87356. /**
  87357. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87358. */
  87359. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87360. __extends(AnaglyphFreeCamera, _super);
  87361. /**
  87362. * Creates a new AnaglyphFreeCamera
  87363. * @param name defines camera name
  87364. * @param position defines initial position
  87365. * @param interaxialDistance defines distance between each color axis
  87366. * @param scene defines the hosting scene
  87367. */
  87368. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87369. var _this = _super.call(this, name, position, scene) || this;
  87370. _this.interaxialDistance = interaxialDistance;
  87371. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87372. return _this;
  87373. }
  87374. /**
  87375. * Gets camera class name
  87376. * @returns AnaglyphFreeCamera
  87377. */
  87378. AnaglyphFreeCamera.prototype.getClassName = function () {
  87379. return "AnaglyphFreeCamera";
  87380. };
  87381. return AnaglyphFreeCamera;
  87382. }(BABYLON.FreeCamera));
  87383. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87384. /**
  87385. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87386. */
  87387. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87388. __extends(AnaglyphArcRotateCamera, _super);
  87389. /**
  87390. * Creates a new AnaglyphArcRotateCamera
  87391. * @param name defines camera name
  87392. * @param alpha defines alpha angle (in radians)
  87393. * @param beta defines beta angle (in radians)
  87394. * @param radius defines radius
  87395. * @param target defines camera target
  87396. * @param interaxialDistance defines distance between each color axis
  87397. * @param scene defines the hosting scene
  87398. */
  87399. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87400. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87401. _this.interaxialDistance = interaxialDistance;
  87402. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87403. return _this;
  87404. }
  87405. /**
  87406. * Gets camera class name
  87407. * @returns AnaglyphArcRotateCamera
  87408. */
  87409. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87410. return "AnaglyphArcRotateCamera";
  87411. };
  87412. return AnaglyphArcRotateCamera;
  87413. }(BABYLON.ArcRotateCamera));
  87414. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87415. /**
  87416. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87417. */
  87418. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87419. __extends(AnaglyphGamepadCamera, _super);
  87420. /**
  87421. * Creates a new AnaglyphGamepadCamera
  87422. * @param name defines camera name
  87423. * @param position defines initial position
  87424. * @param interaxialDistance defines distance between each color axis
  87425. * @param scene defines the hosting scene
  87426. */
  87427. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87428. var _this = _super.call(this, name, position, scene) || this;
  87429. _this.interaxialDistance = interaxialDistance;
  87430. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87431. return _this;
  87432. }
  87433. /**
  87434. * Gets camera class name
  87435. * @returns AnaglyphGamepadCamera
  87436. */
  87437. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87438. return "AnaglyphGamepadCamera";
  87439. };
  87440. return AnaglyphGamepadCamera;
  87441. }(BABYLON.GamepadCamera));
  87442. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87443. /**
  87444. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87445. */
  87446. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87447. __extends(AnaglyphUniversalCamera, _super);
  87448. /**
  87449. * Creates a new AnaglyphUniversalCamera
  87450. * @param name defines camera name
  87451. * @param position defines initial position
  87452. * @param interaxialDistance defines distance between each color axis
  87453. * @param scene defines the hosting scene
  87454. */
  87455. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87456. var _this = _super.call(this, name, position, scene) || this;
  87457. _this.interaxialDistance = interaxialDistance;
  87458. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87459. return _this;
  87460. }
  87461. /**
  87462. * Gets camera class name
  87463. * @returns AnaglyphUniversalCamera
  87464. */
  87465. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87466. return "AnaglyphUniversalCamera";
  87467. };
  87468. return AnaglyphUniversalCamera;
  87469. }(BABYLON.UniversalCamera));
  87470. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87471. /**
  87472. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87473. */
  87474. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87475. __extends(StereoscopicFreeCamera, _super);
  87476. /**
  87477. * Creates a new StereoscopicFreeCamera
  87478. * @param name defines camera name
  87479. * @param position defines initial position
  87480. * @param interaxialDistance defines distance between each color axis
  87481. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87482. * @param scene defines the hosting scene
  87483. */
  87484. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87485. var _this = _super.call(this, name, position, scene) || this;
  87486. _this.interaxialDistance = interaxialDistance;
  87487. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87488. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87489. return _this;
  87490. }
  87491. /**
  87492. * Gets camera class name
  87493. * @returns StereoscopicFreeCamera
  87494. */
  87495. StereoscopicFreeCamera.prototype.getClassName = function () {
  87496. return "StereoscopicFreeCamera";
  87497. };
  87498. return StereoscopicFreeCamera;
  87499. }(BABYLON.FreeCamera));
  87500. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87501. /**
  87502. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87503. */
  87504. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87505. __extends(StereoscopicArcRotateCamera, _super);
  87506. /**
  87507. * Creates a new StereoscopicArcRotateCamera
  87508. * @param name defines camera name
  87509. * @param alpha defines alpha angle (in radians)
  87510. * @param beta defines beta angle (in radians)
  87511. * @param radius defines radius
  87512. * @param target defines camera target
  87513. * @param interaxialDistance defines distance between each color axis
  87514. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87515. * @param scene defines the hosting scene
  87516. */
  87517. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87518. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87519. _this.interaxialDistance = interaxialDistance;
  87520. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87521. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87522. return _this;
  87523. }
  87524. /**
  87525. * Gets camera class name
  87526. * @returns StereoscopicArcRotateCamera
  87527. */
  87528. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87529. return "StereoscopicArcRotateCamera";
  87530. };
  87531. return StereoscopicArcRotateCamera;
  87532. }(BABYLON.ArcRotateCamera));
  87533. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87534. /**
  87535. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87536. */
  87537. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87538. __extends(StereoscopicGamepadCamera, _super);
  87539. /**
  87540. * Creates a new StereoscopicGamepadCamera
  87541. * @param name defines camera name
  87542. * @param position defines initial position
  87543. * @param interaxialDistance defines distance between each color axis
  87544. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87545. * @param scene defines the hosting scene
  87546. */
  87547. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87548. var _this = _super.call(this, name, position, scene) || this;
  87549. _this.interaxialDistance = interaxialDistance;
  87550. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87551. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87552. return _this;
  87553. }
  87554. /**
  87555. * Gets camera class name
  87556. * @returns StereoscopicGamepadCamera
  87557. */
  87558. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87559. return "StereoscopicGamepadCamera";
  87560. };
  87561. return StereoscopicGamepadCamera;
  87562. }(BABYLON.GamepadCamera));
  87563. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87564. /**
  87565. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87566. */
  87567. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87568. __extends(StereoscopicUniversalCamera, _super);
  87569. /**
  87570. * Creates a new StereoscopicUniversalCamera
  87571. * @param name defines camera name
  87572. * @param position defines initial position
  87573. * @param interaxialDistance defines distance between each color axis
  87574. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87575. * @param scene defines the hosting scene
  87576. */
  87577. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87578. var _this = _super.call(this, name, position, scene) || this;
  87579. _this.interaxialDistance = interaxialDistance;
  87580. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87581. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87582. return _this;
  87583. }
  87584. /**
  87585. * Gets camera class name
  87586. * @returns StereoscopicUniversalCamera
  87587. */
  87588. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87589. return "StereoscopicUniversalCamera";
  87590. };
  87591. return StereoscopicUniversalCamera;
  87592. }(BABYLON.UniversalCamera));
  87593. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87594. })(BABYLON || (BABYLON = {}));
  87595. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87596. var BABYLON;
  87597. (function (BABYLON) {
  87598. var VRExperienceHelperGazer = /** @class */ (function () {
  87599. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87600. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87601. this.scene = scene;
  87602. this._pointerDownOnMeshAsked = false;
  87603. this._isActionableMesh = false;
  87604. this._teleportationRequestInitiated = false;
  87605. this._teleportationBackRequestInitiated = false;
  87606. this._rotationRightAsked = false;
  87607. this._rotationLeftAsked = false;
  87608. this._dpadPressed = true;
  87609. this._activePointer = false;
  87610. this._id = VRExperienceHelperGazer._idCounter++;
  87611. // Gaze tracker
  87612. if (!gazeTrackerToClone) {
  87613. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87614. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87615. this._gazeTracker.isPickable = false;
  87616. this._gazeTracker.isVisible = false;
  87617. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87618. targetMat.specularColor = BABYLON.Color3.Black();
  87619. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87620. targetMat.backFaceCulling = false;
  87621. this._gazeTracker.material = targetMat;
  87622. }
  87623. else {
  87624. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87625. }
  87626. }
  87627. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87628. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87629. };
  87630. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87631. this._pointerDownOnMeshAsked = true;
  87632. if (this._currentMeshSelected && this._currentHit) {
  87633. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87634. }
  87635. };
  87636. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87637. if (this._currentMeshSelected && this._currentHit) {
  87638. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87639. }
  87640. this._pointerDownOnMeshAsked = false;
  87641. };
  87642. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87643. this._activePointer = true;
  87644. };
  87645. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87646. this._activePointer = false;
  87647. };
  87648. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87649. if (distance === void 0) { distance = 100; }
  87650. };
  87651. VRExperienceHelperGazer.prototype.dispose = function () {
  87652. this._interactionsEnabled = false;
  87653. this._teleportationEnabled = false;
  87654. if (this._gazeTracker) {
  87655. this._gazeTracker.dispose();
  87656. }
  87657. };
  87658. VRExperienceHelperGazer._idCounter = 0;
  87659. return VRExperienceHelperGazer;
  87660. }());
  87661. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87662. __extends(VRExperienceHelperControllerGazer, _super);
  87663. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87664. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87665. _this.webVRController = webVRController;
  87666. // Laser pointer
  87667. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87668. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87669. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87670. laserPointerMaterial.alpha = 0.6;
  87671. _this._laserPointer.material = laserPointerMaterial;
  87672. _this._laserPointer.rotation.x = Math.PI / 2;
  87673. _this._laserPointer.position.z = -0.5;
  87674. _this._laserPointer.isVisible = false;
  87675. if (!webVRController.mesh) {
  87676. // Create an empty mesh that is used prior to loading the high quality model
  87677. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87678. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87679. preloadPointerPose.rotation.x = -0.7;
  87680. preloadMesh.addChild(preloadPointerPose);
  87681. webVRController.attachToMesh(preloadMesh);
  87682. }
  87683. _this._setLaserPointerParent(webVRController.mesh);
  87684. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87685. _this._setLaserPointerParent(mesh);
  87686. });
  87687. return _this;
  87688. }
  87689. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87690. return this.webVRController.getForwardRay(length);
  87691. };
  87692. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87693. _super.prototype._activatePointer.call(this);
  87694. this._laserPointer.isVisible = true;
  87695. };
  87696. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87697. _super.prototype._deactivatePointer.call(this);
  87698. this._laserPointer.isVisible = false;
  87699. };
  87700. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87701. this._laserPointer.material.emissiveColor = color;
  87702. };
  87703. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87704. var makeNotPick = function (root) {
  87705. root.name += " laserPointer";
  87706. root.getChildMeshes().forEach(function (c) {
  87707. makeNotPick(c);
  87708. });
  87709. };
  87710. makeNotPick(mesh);
  87711. var childMeshes = mesh.getChildMeshes();
  87712. this.webVRController._pointingPoseNode = null;
  87713. for (var i = 0; i < childMeshes.length; i++) {
  87714. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87715. mesh = childMeshes[i];
  87716. this.webVRController._pointingPoseNode = mesh;
  87717. break;
  87718. }
  87719. }
  87720. this._laserPointer.parent = mesh;
  87721. };
  87722. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87723. if (distance === void 0) { distance = 100; }
  87724. this._laserPointer.scaling.y = distance;
  87725. this._laserPointer.position.z = -distance / 2;
  87726. };
  87727. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87728. _super.prototype.dispose.call(this);
  87729. this._laserPointer.dispose();
  87730. if (this._meshAttachedObserver) {
  87731. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87732. }
  87733. };
  87734. return VRExperienceHelperControllerGazer;
  87735. }(VRExperienceHelperGazer));
  87736. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87737. __extends(VRExperienceHelperCameraGazer, _super);
  87738. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87739. var _this = _super.call(this, scene) || this;
  87740. _this.getCamera = getCamera;
  87741. return _this;
  87742. }
  87743. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87744. var camera = this.getCamera();
  87745. if (camera) {
  87746. return camera.getForwardRay(length);
  87747. }
  87748. else {
  87749. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87750. }
  87751. };
  87752. return VRExperienceHelperCameraGazer;
  87753. }(VRExperienceHelperGazer));
  87754. /**
  87755. * Helps to quickly add VR support to an existing scene.
  87756. * See http://doc.babylonjs.com/how_to/webvr_helper
  87757. */
  87758. var VRExperienceHelper = /** @class */ (function () {
  87759. /**
  87760. * Instantiates a VRExperienceHelper.
  87761. * Helps to quickly add VR support to an existing scene.
  87762. * @param scene The scene the VRExperienceHelper belongs to.
  87763. * @param webVROptions Options to modify the vr experience helper's behavior.
  87764. */
  87765. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87766. if (webVROptions === void 0) { webVROptions = {}; }
  87767. var _this = this;
  87768. this.webVROptions = webVROptions;
  87769. // Can the system support WebVR, even if a headset isn't plugged in?
  87770. this._webVRsupported = false;
  87771. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87772. this._webVRready = false;
  87773. // Are we waiting for the requestPresent callback to complete?
  87774. this._webVRrequesting = false;
  87775. // Are we presenting to the headset right now?
  87776. this._webVRpresenting = false;
  87777. // Are we presenting in the fullscreen fallback?
  87778. this._fullscreenVRpresenting = false;
  87779. /**
  87780. * Observable raised when entering VR.
  87781. */
  87782. this.onEnteringVRObservable = new BABYLON.Observable();
  87783. /**
  87784. * Observable raised when exiting VR.
  87785. */
  87786. this.onExitingVRObservable = new BABYLON.Observable();
  87787. /**
  87788. * Observable raised when controller mesh is loaded.
  87789. */
  87790. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87791. this._useCustomVRButton = false;
  87792. this._teleportationRequested = false;
  87793. this._teleportActive = false;
  87794. this._floorMeshesCollection = [];
  87795. this._rotationAllowed = true;
  87796. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87797. this._isDefaultTeleportationTarget = true;
  87798. this._teleportationFillColor = "#444444";
  87799. this._teleportationBorderColor = "#FFFFFF";
  87800. this._rotationAngle = 0;
  87801. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87802. this._padSensibilityUp = 0.65;
  87803. this._padSensibilityDown = 0.35;
  87804. this.leftController = null;
  87805. this.rightController = null;
  87806. /**
  87807. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87808. */
  87809. this.onNewMeshSelected = new BABYLON.Observable();
  87810. /**
  87811. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87812. */
  87813. this.onNewMeshPicked = new BABYLON.Observable();
  87814. /**
  87815. * Observable raised before camera teleportation
  87816. */
  87817. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87818. /**
  87819. * Observable raised after camera teleportation
  87820. */
  87821. this.onAfterCameraTeleport = new BABYLON.Observable();
  87822. /**
  87823. * Observable raised when current selected mesh gets unselected
  87824. */
  87825. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87826. /**
  87827. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87828. */
  87829. this.teleportationEnabled = true;
  87830. this._teleportationInitialized = false;
  87831. this._interactionsEnabled = false;
  87832. this._interactionsRequested = false;
  87833. this._displayGaze = true;
  87834. this._displayLaserPointer = true;
  87835. this._onResize = function () {
  87836. _this.moveButtonToBottomRight();
  87837. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87838. _this.exitVR();
  87839. }
  87840. };
  87841. this._onFullscreenChange = function () {
  87842. if (document.fullscreen !== undefined) {
  87843. _this._fullscreenVRpresenting = document.fullscreen;
  87844. }
  87845. else if (document.mozFullScreen !== undefined) {
  87846. _this._fullscreenVRpresenting = document.mozFullScreen;
  87847. }
  87848. else if (document.webkitIsFullScreen !== undefined) {
  87849. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87850. }
  87851. else if (document.msIsFullScreen !== undefined) {
  87852. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87853. }
  87854. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87855. _this.exitVR();
  87856. if (!_this._useCustomVRButton) {
  87857. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87858. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87859. }
  87860. }
  87861. };
  87862. this.beforeRender = function () {
  87863. if (_this.leftController && _this.leftController._activePointer) {
  87864. _this._castRayAndSelectObject(_this.leftController);
  87865. }
  87866. if (_this.rightController && _this.rightController._activePointer) {
  87867. _this._castRayAndSelectObject(_this.rightController);
  87868. }
  87869. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87870. _this._castRayAndSelectObject(_this._cameraGazer);
  87871. }
  87872. else {
  87873. _this._cameraGazer._gazeTracker.isVisible = false;
  87874. }
  87875. };
  87876. this._onNewGamepadConnected = function (gamepad) {
  87877. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87878. if (gamepad.leftStick) {
  87879. gamepad.onleftstickchanged(function (stickValues) {
  87880. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87881. // Listening to classic/xbox gamepad only if no VR controller is active
  87882. if ((!_this.leftController && !_this.rightController) ||
  87883. ((_this.leftController && !_this.leftController._activePointer) &&
  87884. (_this.rightController && !_this.rightController._activePointer))) {
  87885. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87886. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87887. }
  87888. }
  87889. });
  87890. }
  87891. if (gamepad.rightStick) {
  87892. gamepad.onrightstickchanged(function (stickValues) {
  87893. if (_this._teleportationInitialized) {
  87894. _this._checkRotate(stickValues, _this._cameraGazer);
  87895. }
  87896. });
  87897. }
  87898. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87899. gamepad.onbuttondown(function (buttonPressed) {
  87900. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87901. _this._cameraGazer._selectionPointerDown();
  87902. }
  87903. });
  87904. gamepad.onbuttonup(function (buttonPressed) {
  87905. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87906. _this._cameraGazer._selectionPointerUp();
  87907. }
  87908. });
  87909. }
  87910. }
  87911. else {
  87912. var webVRController = gamepad;
  87913. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87914. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87915. _this.rightController = controller;
  87916. }
  87917. else {
  87918. _this.leftController = controller;
  87919. }
  87920. _this._tryEnableInteractionOnController(controller);
  87921. }
  87922. };
  87923. // 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
  87924. this._tryEnableInteractionOnController = function (controller) {
  87925. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87926. _this._enableInteractionOnController(controller);
  87927. }
  87928. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87929. _this._enableTeleportationOnController(controller);
  87930. }
  87931. };
  87932. this._onNewGamepadDisconnected = function (gamepad) {
  87933. if (gamepad instanceof BABYLON.WebVRController) {
  87934. if (gamepad.hand === "left" && _this.leftController != null) {
  87935. _this.leftController.dispose();
  87936. _this.leftController = null;
  87937. }
  87938. if (gamepad.hand === "right" && _this.rightController != null) {
  87939. _this.rightController.dispose();
  87940. _this.rightController = null;
  87941. }
  87942. }
  87943. };
  87944. this._workingVector = BABYLON.Vector3.Zero();
  87945. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87946. this._workingMatrix = BABYLON.Matrix.Identity();
  87947. this._scene = scene;
  87948. this._canvas = scene.getEngine().getRenderingCanvas();
  87949. // Parse options
  87950. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87951. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87952. }
  87953. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87954. webVROptions.createDeviceOrientationCamera = true;
  87955. }
  87956. if (webVROptions.defaultHeight === undefined) {
  87957. webVROptions.defaultHeight = 1.7;
  87958. }
  87959. if (webVROptions.useCustomVRButton) {
  87960. this._useCustomVRButton = true;
  87961. if (webVROptions.customVRButton) {
  87962. this._btnVR = webVROptions.customVRButton;
  87963. }
  87964. }
  87965. if (webVROptions.rayLength) {
  87966. this._rayLength = webVROptions.rayLength;
  87967. }
  87968. this._defaultHeight = webVROptions.defaultHeight;
  87969. if (webVROptions.positionScale) {
  87970. this._rayLength *= webVROptions.positionScale;
  87971. this._defaultHeight *= webVROptions.positionScale;
  87972. }
  87973. // Set position
  87974. if (this._scene.activeCamera) {
  87975. this._position = this._scene.activeCamera.position.clone();
  87976. }
  87977. else {
  87978. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87979. }
  87980. // Set non-vr camera
  87981. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87982. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87983. // Copy data from existing camera
  87984. if (this._scene.activeCamera) {
  87985. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87986. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87987. // Set rotation from previous camera
  87988. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87989. var targetCamera = this._scene.activeCamera;
  87990. if (targetCamera.rotationQuaternion) {
  87991. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87992. }
  87993. else {
  87994. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87995. }
  87996. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87997. }
  87998. }
  87999. this._scene.activeCamera = this._deviceOrientationCamera;
  88000. if (this._canvas) {
  88001. this._scene.activeCamera.attachControl(this._canvas);
  88002. }
  88003. }
  88004. else {
  88005. this._existingCamera = this._scene.activeCamera;
  88006. }
  88007. // Create VR cameras
  88008. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88009. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88010. }
  88011. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88012. this._webVRCamera.useStandingMatrix();
  88013. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88014. // Create default button
  88015. if (!this._useCustomVRButton) {
  88016. this._btnVR = document.createElement("BUTTON");
  88017. this._btnVR.className = "babylonVRicon";
  88018. this._btnVR.id = "babylonVRiconbtn";
  88019. this._btnVR.title = "Click to switch to VR";
  88020. 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) }";
  88021. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88022. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88023. // css += ".babylonVRicon.vrdisplaysupported { }";
  88024. // css += ".babylonVRicon.vrdisplayready { }";
  88025. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88026. var style = document.createElement('style');
  88027. style.appendChild(document.createTextNode(css));
  88028. document.getElementsByTagName('head')[0].appendChild(style);
  88029. this.moveButtonToBottomRight();
  88030. }
  88031. // VR button click event
  88032. if (this._btnVR) {
  88033. this._btnVR.addEventListener("click", function () {
  88034. if (!_this.isInVRMode) {
  88035. _this.enterVR();
  88036. }
  88037. else {
  88038. _this.exitVR();
  88039. }
  88040. });
  88041. }
  88042. // Window events
  88043. window.addEventListener("resize", this._onResize);
  88044. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88045. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88046. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88047. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88048. // Display vr button when headset is connected
  88049. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88050. this.displayVRButton();
  88051. }
  88052. else {
  88053. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88054. if (e.vrDisplay) {
  88055. _this.displayVRButton();
  88056. }
  88057. });
  88058. }
  88059. // Exiting VR mode using 'ESC' key on desktop
  88060. this._onKeyDown = function (event) {
  88061. if (event.keyCode === 27 && _this.isInVRMode) {
  88062. _this.exitVR();
  88063. }
  88064. };
  88065. document.addEventListener("keydown", this._onKeyDown);
  88066. // Exiting VR mode double tapping the touch screen
  88067. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88068. if (_this.isInVRMode) {
  88069. _this.exitVR();
  88070. if (_this._fullscreenVRpresenting) {
  88071. _this._scene.getEngine().switchFullscreen(true);
  88072. }
  88073. }
  88074. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88075. // Listen for WebVR display changes
  88076. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88077. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88078. this._onVRRequestPresentStart = function () {
  88079. _this._webVRrequesting = true;
  88080. _this.updateButtonVisibility();
  88081. };
  88082. this._onVRRequestPresentComplete = function (success) {
  88083. _this._webVRrequesting = false;
  88084. _this.updateButtonVisibility();
  88085. };
  88086. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88087. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88088. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88089. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88090. scene.onDisposeObservable.add(function () {
  88091. _this.dispose();
  88092. });
  88093. // Gamepad connection events
  88094. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88095. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88096. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88097. this.updateButtonVisibility();
  88098. //create easing functions
  88099. this._circleEase = new BABYLON.CircleEase();
  88100. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88101. }
  88102. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88103. /** Return this.onEnteringVRObservable
  88104. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88105. */
  88106. get: function () {
  88107. return this.onEnteringVRObservable;
  88108. },
  88109. enumerable: true,
  88110. configurable: true
  88111. });
  88112. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88113. /** Return this.onExitingVRObservable
  88114. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88115. */
  88116. get: function () {
  88117. return this.onExitingVRObservable;
  88118. },
  88119. enumerable: true,
  88120. configurable: true
  88121. });
  88122. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88123. /** Return this.onControllerMeshLoadedObservable
  88124. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88125. */
  88126. get: function () {
  88127. return this.onControllerMeshLoadedObservable;
  88128. },
  88129. enumerable: true,
  88130. configurable: true
  88131. });
  88132. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88133. /**
  88134. * The mesh used to display where the user is going to teleport.
  88135. */
  88136. get: function () {
  88137. return this._teleportationTarget;
  88138. },
  88139. /**
  88140. * Sets the mesh to be used to display where the user is going to teleport.
  88141. */
  88142. set: function (value) {
  88143. if (value) {
  88144. value.name = "teleportationTarget";
  88145. this._isDefaultTeleportationTarget = false;
  88146. this._teleportationTarget = value;
  88147. }
  88148. },
  88149. enumerable: true,
  88150. configurable: true
  88151. });
  88152. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88153. /**
  88154. * The mesh used to display where the user is selecting,
  88155. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88156. * See http://doc.babylonjs.com/resources/baking_transformations
  88157. */
  88158. get: function () {
  88159. return this._cameraGazer._gazeTracker;
  88160. },
  88161. set: function (value) {
  88162. if (value) {
  88163. this._cameraGazer._gazeTracker = value;
  88164. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88165. this._cameraGazer._gazeTracker.isPickable = false;
  88166. this._cameraGazer._gazeTracker.isVisible = false;
  88167. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88168. if (this.leftController) {
  88169. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88170. }
  88171. if (this.rightController) {
  88172. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88173. }
  88174. }
  88175. },
  88176. enumerable: true,
  88177. configurable: true
  88178. });
  88179. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88180. /**
  88181. * If the ray of the gaze should be displayed.
  88182. */
  88183. get: function () {
  88184. return this._displayGaze;
  88185. },
  88186. /**
  88187. * Sets if the ray of the gaze should be displayed.
  88188. */
  88189. set: function (value) {
  88190. this._displayGaze = value;
  88191. if (!value) {
  88192. this._cameraGazer._gazeTracker.isVisible = false;
  88193. if (this.leftController) {
  88194. this.leftController._gazeTracker.isVisible = false;
  88195. }
  88196. if (this.rightController) {
  88197. this.rightController._gazeTracker.isVisible = false;
  88198. }
  88199. }
  88200. },
  88201. enumerable: true,
  88202. configurable: true
  88203. });
  88204. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88205. /**
  88206. * If the ray of the LaserPointer should be displayed.
  88207. */
  88208. get: function () {
  88209. return this._displayLaserPointer;
  88210. },
  88211. /**
  88212. * Sets if the ray of the LaserPointer should be displayed.
  88213. */
  88214. set: function (value) {
  88215. this._displayLaserPointer = value;
  88216. if (!value) {
  88217. if (this.rightController) {
  88218. this.rightController._deactivatePointer();
  88219. this.rightController._gazeTracker.isVisible = false;
  88220. }
  88221. if (this.leftController) {
  88222. this.leftController._deactivatePointer();
  88223. this.leftController._gazeTracker.isVisible = false;
  88224. }
  88225. }
  88226. else {
  88227. if (this.rightController) {
  88228. this.rightController._activatePointer();
  88229. }
  88230. if (this.leftController) {
  88231. this.leftController._activatePointer();
  88232. }
  88233. }
  88234. },
  88235. enumerable: true,
  88236. configurable: true
  88237. });
  88238. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88239. /**
  88240. * The deviceOrientationCamera used as the camera when not in VR.
  88241. */
  88242. get: function () {
  88243. return this._deviceOrientationCamera;
  88244. },
  88245. enumerable: true,
  88246. configurable: true
  88247. });
  88248. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88249. /**
  88250. * Based on the current WebVR support, returns the current VR camera used.
  88251. */
  88252. get: function () {
  88253. if (this._webVRready) {
  88254. return this._webVRCamera;
  88255. }
  88256. else {
  88257. return this._scene.activeCamera;
  88258. }
  88259. },
  88260. enumerable: true,
  88261. configurable: true
  88262. });
  88263. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88264. /**
  88265. * The webVRCamera which is used when in VR.
  88266. */
  88267. get: function () {
  88268. return this._webVRCamera;
  88269. },
  88270. enumerable: true,
  88271. configurable: true
  88272. });
  88273. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88274. /**
  88275. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88276. */
  88277. get: function () {
  88278. return this._vrDeviceOrientationCamera;
  88279. },
  88280. enumerable: true,
  88281. configurable: true
  88282. });
  88283. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88284. get: function () {
  88285. var result = this._cameraGazer._teleportationRequestInitiated
  88286. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88287. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88288. return result;
  88289. },
  88290. enumerable: true,
  88291. configurable: true
  88292. });
  88293. // Raised when one of the controller has loaded successfully its associated default mesh
  88294. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88295. if (this.leftController && this.leftController.webVRController == webVRController) {
  88296. if (webVRController.mesh) {
  88297. this.leftController._setLaserPointerParent(webVRController.mesh);
  88298. }
  88299. }
  88300. if (this.rightController && this.rightController.webVRController == webVRController) {
  88301. if (webVRController.mesh) {
  88302. this.rightController._setLaserPointerParent(webVRController.mesh);
  88303. }
  88304. }
  88305. try {
  88306. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88307. }
  88308. catch (err) {
  88309. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88310. }
  88311. };
  88312. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88313. /**
  88314. * Gets a value indicating if we are currently in VR mode.
  88315. */
  88316. get: function () {
  88317. return this._webVRpresenting || this._fullscreenVRpresenting;
  88318. },
  88319. enumerable: true,
  88320. configurable: true
  88321. });
  88322. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88323. var vrDisplay = this._scene.getEngine().getVRDevice();
  88324. if (vrDisplay) {
  88325. var wasPresenting = this._webVRpresenting;
  88326. // A VR display is connected
  88327. this._webVRpresenting = vrDisplay.isPresenting;
  88328. if (wasPresenting && !this._webVRpresenting)
  88329. this.exitVR();
  88330. }
  88331. else {
  88332. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88333. }
  88334. this.updateButtonVisibility();
  88335. };
  88336. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88337. this._webVRsupported = eventArgs.vrSupported;
  88338. this._webVRready = !!eventArgs.vrDisplay;
  88339. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88340. this.updateButtonVisibility();
  88341. };
  88342. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88343. if (this._canvas && !this._useCustomVRButton) {
  88344. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88345. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88346. }
  88347. };
  88348. VRExperienceHelper.prototype.displayVRButton = function () {
  88349. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88350. document.body.appendChild(this._btnVR);
  88351. this._btnVRDisplayed = true;
  88352. }
  88353. };
  88354. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88355. if (!this._btnVR || this._useCustomVRButton) {
  88356. return;
  88357. }
  88358. this._btnVR.className = "babylonVRicon";
  88359. if (this.isInVRMode) {
  88360. this._btnVR.className += " vrdisplaypresenting";
  88361. }
  88362. else {
  88363. if (this._webVRready)
  88364. this._btnVR.className += " vrdisplayready";
  88365. if (this._webVRsupported)
  88366. this._btnVR.className += " vrdisplaysupported";
  88367. if (this._webVRrequesting)
  88368. this._btnVR.className += " vrdisplayrequesting";
  88369. }
  88370. };
  88371. /**
  88372. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88373. * Otherwise, will use the fullscreen API.
  88374. */
  88375. VRExperienceHelper.prototype.enterVR = function () {
  88376. if (this.onEnteringVRObservable) {
  88377. try {
  88378. this.onEnteringVRObservable.notifyObservers(this);
  88379. }
  88380. catch (err) {
  88381. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88382. }
  88383. }
  88384. if (this._scene.activeCamera) {
  88385. this._position = this._scene.activeCamera.position.clone();
  88386. // make sure that we return to the last active camera
  88387. this._existingCamera = this._scene.activeCamera;
  88388. }
  88389. if (this._webVRrequesting)
  88390. return;
  88391. // If WebVR is supported and a headset is connected
  88392. if (this._webVRready) {
  88393. if (!this._webVRpresenting) {
  88394. this._webVRCamera.position = this._position;
  88395. this._scene.activeCamera = this._webVRCamera;
  88396. }
  88397. }
  88398. else if (this._vrDeviceOrientationCamera) {
  88399. this._vrDeviceOrientationCamera.position = this._position;
  88400. if (this._scene.activeCamera) {
  88401. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88402. }
  88403. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88404. this._scene.getEngine().switchFullscreen(true);
  88405. this.updateButtonVisibility();
  88406. }
  88407. if (this._scene.activeCamera && this._canvas) {
  88408. this._scene.activeCamera.attachControl(this._canvas);
  88409. }
  88410. if (this._interactionsEnabled) {
  88411. this._scene.registerBeforeRender(this.beforeRender);
  88412. }
  88413. };
  88414. /**
  88415. * Attempt to exit VR, or fullscreen.
  88416. */
  88417. VRExperienceHelper.prototype.exitVR = function () {
  88418. if (this.onExitingVRObservable) {
  88419. try {
  88420. this.onExitingVRObservable.notifyObservers(this);
  88421. }
  88422. catch (err) {
  88423. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88424. }
  88425. }
  88426. if (this._webVRpresenting) {
  88427. this._scene.getEngine().disableVR();
  88428. }
  88429. if (this._scene.activeCamera) {
  88430. this._position = this._scene.activeCamera.position.clone();
  88431. }
  88432. if (this._deviceOrientationCamera) {
  88433. this._deviceOrientationCamera.position = this._position;
  88434. this._scene.activeCamera = this._deviceOrientationCamera;
  88435. if (this._canvas) {
  88436. this._scene.activeCamera.attachControl(this._canvas);
  88437. }
  88438. }
  88439. else if (this._existingCamera) {
  88440. this._existingCamera.position = this._position;
  88441. this._scene.activeCamera = this._existingCamera;
  88442. }
  88443. this.updateButtonVisibility();
  88444. if (this._interactionsEnabled) {
  88445. this._scene.unregisterBeforeRender(this.beforeRender);
  88446. }
  88447. // resize to update width and height when exiting vr exits fullscreen
  88448. this._scene.getEngine().resize();
  88449. };
  88450. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88451. /**
  88452. * The position of the vr experience helper.
  88453. */
  88454. get: function () {
  88455. return this._position;
  88456. },
  88457. /**
  88458. * Sets the position of the vr experience helper.
  88459. */
  88460. set: function (value) {
  88461. this._position = value;
  88462. if (this._scene.activeCamera) {
  88463. this._scene.activeCamera.position = value;
  88464. }
  88465. },
  88466. enumerable: true,
  88467. configurable: true
  88468. });
  88469. /**
  88470. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88471. */
  88472. VRExperienceHelper.prototype.enableInteractions = function () {
  88473. var _this = this;
  88474. if (!this._interactionsEnabled) {
  88475. this._interactionsRequested = true;
  88476. if (this.leftController) {
  88477. this._enableInteractionOnController(this.leftController);
  88478. }
  88479. if (this.rightController) {
  88480. this._enableInteractionOnController(this.rightController);
  88481. }
  88482. this.raySelectionPredicate = function (mesh) {
  88483. return mesh.isVisible;
  88484. };
  88485. this.meshSelectionPredicate = function (mesh) {
  88486. return true;
  88487. };
  88488. this._raySelectionPredicate = function (mesh) {
  88489. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88490. && mesh.name.indexOf("teleportationTarget") === -1
  88491. && mesh.name.indexOf("torusTeleportation") === -1
  88492. && mesh.name.indexOf("laserPointer") === -1)) {
  88493. return _this.raySelectionPredicate(mesh);
  88494. }
  88495. return false;
  88496. };
  88497. this._interactionsEnabled = true;
  88498. }
  88499. };
  88500. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88501. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88502. if (this._floorMeshesCollection[i].id === mesh.id) {
  88503. return true;
  88504. }
  88505. }
  88506. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88507. return true;
  88508. }
  88509. return false;
  88510. };
  88511. /**
  88512. * Adds a floor mesh to be used for teleportation.
  88513. * @param floorMesh the mesh to be used for teleportation.
  88514. */
  88515. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88516. if (!this._floorMeshesCollection) {
  88517. return;
  88518. }
  88519. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88520. return;
  88521. }
  88522. this._floorMeshesCollection.push(floorMesh);
  88523. };
  88524. /**
  88525. * Removes a floor mesh from being used for teleportation.
  88526. * @param floorMesh the mesh to be removed.
  88527. */
  88528. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88529. if (!this._floorMeshesCollection) {
  88530. return;
  88531. }
  88532. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88533. if (meshIndex !== -1) {
  88534. this._floorMeshesCollection.splice(meshIndex, 1);
  88535. }
  88536. };
  88537. /**
  88538. * Enables interactions and teleportation using the VR controllers and gaze.
  88539. * @param vrTeleportationOptions options to modify teleportation behavior.
  88540. */
  88541. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88542. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88543. if (!this._teleportationInitialized) {
  88544. this._teleportationRequested = true;
  88545. this.enableInteractions();
  88546. if (vrTeleportationOptions.floorMeshName) {
  88547. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88548. }
  88549. if (vrTeleportationOptions.floorMeshes) {
  88550. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88551. }
  88552. if (this.leftController != null) {
  88553. this._enableTeleportationOnController(this.leftController);
  88554. }
  88555. if (this.rightController != null) {
  88556. this._enableTeleportationOnController(this.rightController);
  88557. }
  88558. // Creates an image processing post process for the vignette not relying
  88559. // on the main scene configuration for image processing to reduce setup and spaces
  88560. // (gamma/linear) conflicts.
  88561. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88562. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88563. imageProcessingConfiguration.vignetteEnabled = true;
  88564. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88565. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88566. this._teleportationInitialized = true;
  88567. if (this._isDefaultTeleportationTarget) {
  88568. this._createTeleportationCircles();
  88569. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88570. }
  88571. }
  88572. };
  88573. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88574. var _this = this;
  88575. var controllerMesh = controller.webVRController.mesh;
  88576. if (controllerMesh) {
  88577. controller._interactionsEnabled = true;
  88578. controller._activatePointer();
  88579. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88580. // Enabling / disabling laserPointer
  88581. if (_this._displayLaserPointer && stateObject.value === 1) {
  88582. if (controller._activePointer) {
  88583. controller._deactivatePointer();
  88584. }
  88585. else {
  88586. controller._activatePointer();
  88587. }
  88588. if (_this.displayGaze) {
  88589. controller._gazeTracker.isVisible = controller._activePointer;
  88590. }
  88591. }
  88592. });
  88593. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88594. if (!controller._pointerDownOnMeshAsked) {
  88595. if (stateObject.value > _this._padSensibilityUp) {
  88596. controller._selectionPointerDown();
  88597. }
  88598. }
  88599. else if (stateObject.value < _this._padSensibilityDown) {
  88600. controller._selectionPointerUp();
  88601. }
  88602. });
  88603. }
  88604. };
  88605. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88606. // Dont teleport if another gaze already requested teleportation
  88607. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88608. return;
  88609. }
  88610. if (!gazer._teleportationRequestInitiated) {
  88611. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88612. gazer._activatePointer();
  88613. gazer._teleportationRequestInitiated = true;
  88614. }
  88615. }
  88616. else {
  88617. // Listening to the proper controller values changes to confirm teleportation
  88618. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88619. if (this._teleportActive) {
  88620. this._teleportCamera(this._haloCenter);
  88621. }
  88622. gazer._teleportationRequestInitiated = false;
  88623. }
  88624. }
  88625. };
  88626. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88627. // Only rotate when user is not currently selecting a teleportation location
  88628. if (gazer._teleportationRequestInitiated) {
  88629. return;
  88630. }
  88631. if (!gazer._rotationLeftAsked) {
  88632. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88633. gazer._rotationLeftAsked = true;
  88634. if (this._rotationAllowed) {
  88635. this._rotateCamera(false);
  88636. }
  88637. }
  88638. }
  88639. else {
  88640. if (stateObject.x > -this._padSensibilityDown) {
  88641. gazer._rotationLeftAsked = false;
  88642. }
  88643. }
  88644. if (!gazer._rotationRightAsked) {
  88645. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88646. gazer._rotationRightAsked = true;
  88647. if (this._rotationAllowed) {
  88648. this._rotateCamera(true);
  88649. }
  88650. }
  88651. }
  88652. else {
  88653. if (stateObject.x < this._padSensibilityDown) {
  88654. gazer._rotationRightAsked = false;
  88655. }
  88656. }
  88657. };
  88658. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88659. // Only teleport backwards when user is not currently selecting a teleportation location
  88660. if (gazer._teleportationRequestInitiated) {
  88661. return;
  88662. }
  88663. // Teleport backwards
  88664. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88665. if (!gazer._teleportationBackRequestInitiated) {
  88666. if (!this.currentVRCamera) {
  88667. return;
  88668. }
  88669. // Get rotation and position of the current camera
  88670. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88671. var position = this.currentVRCamera.position;
  88672. // If the camera has device position, use that instead
  88673. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88674. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88675. position = this.currentVRCamera.devicePosition;
  88676. }
  88677. // Get matrix with only the y rotation of the device rotation
  88678. rotation.toEulerAnglesToRef(this._workingVector);
  88679. this._workingVector.z = 0;
  88680. this._workingVector.x = 0;
  88681. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88682. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88683. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88684. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88685. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88686. var ray = new BABYLON.Ray(position, this._workingVector);
  88687. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88688. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88689. this._teleportCamera(hit.pickedPoint);
  88690. }
  88691. gazer._teleportationBackRequestInitiated = true;
  88692. }
  88693. }
  88694. else {
  88695. gazer._teleportationBackRequestInitiated = false;
  88696. }
  88697. };
  88698. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88699. var _this = this;
  88700. var controllerMesh = controller.webVRController.mesh;
  88701. if (controllerMesh) {
  88702. if (!controller._interactionsEnabled) {
  88703. this._enableInteractionOnController(controller);
  88704. }
  88705. controller._interactionsEnabled = true;
  88706. controller._teleportationEnabled = true;
  88707. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88708. controller._dpadPressed = false;
  88709. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88710. controller._dpadPressed = stateObject.pressed;
  88711. if (!controller._dpadPressed) {
  88712. controller._rotationLeftAsked = false;
  88713. controller._rotationRightAsked = false;
  88714. controller._teleportationBackRequestInitiated = false;
  88715. }
  88716. });
  88717. }
  88718. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88719. if (_this.teleportationEnabled) {
  88720. _this._checkTeleportBackwards(stateObject, controller);
  88721. _this._checkTeleportWithRay(stateObject, controller);
  88722. }
  88723. _this._checkRotate(stateObject, controller);
  88724. });
  88725. }
  88726. };
  88727. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88728. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88729. this._teleportationTarget.isPickable = false;
  88730. var length = 512;
  88731. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88732. dynamicTexture.hasAlpha = true;
  88733. var context = dynamicTexture.getContext();
  88734. var centerX = length / 2;
  88735. var centerY = length / 2;
  88736. var radius = 200;
  88737. context.beginPath();
  88738. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88739. context.fillStyle = this._teleportationFillColor;
  88740. context.fill();
  88741. context.lineWidth = 10;
  88742. context.strokeStyle = this._teleportationBorderColor;
  88743. context.stroke();
  88744. context.closePath();
  88745. dynamicTexture.update();
  88746. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88747. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88748. this._teleportationTarget.material = teleportationCircleMaterial;
  88749. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88750. torus.isPickable = false;
  88751. torus.parent = this._teleportationTarget;
  88752. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88753. var keys = [];
  88754. keys.push({
  88755. frame: 0,
  88756. value: 0
  88757. });
  88758. keys.push({
  88759. frame: 30,
  88760. value: 0.4
  88761. });
  88762. keys.push({
  88763. frame: 60,
  88764. value: 0
  88765. });
  88766. animationInnerCircle.setKeys(keys);
  88767. var easingFunction = new BABYLON.SineEase();
  88768. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88769. animationInnerCircle.setEasingFunction(easingFunction);
  88770. torus.animations = [];
  88771. torus.animations.push(animationInnerCircle);
  88772. this._scene.beginAnimation(torus, 0, 60, true);
  88773. this._hideTeleportationTarget();
  88774. };
  88775. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88776. this._teleportActive = true;
  88777. if (this._teleportationInitialized) {
  88778. this._teleportationTarget.isVisible = true;
  88779. if (this._isDefaultTeleportationTarget) {
  88780. this._teleportationTarget.getChildren()[0].isVisible = true;
  88781. }
  88782. }
  88783. };
  88784. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88785. this._teleportActive = false;
  88786. if (this._teleportationInitialized) {
  88787. this._teleportationTarget.isVisible = false;
  88788. if (this._isDefaultTeleportationTarget) {
  88789. this._teleportationTarget.getChildren()[0].isVisible = false;
  88790. }
  88791. }
  88792. };
  88793. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88794. var _this = this;
  88795. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88796. return;
  88797. }
  88798. if (right) {
  88799. this._rotationAngle++;
  88800. }
  88801. else {
  88802. this._rotationAngle--;
  88803. }
  88804. this.currentVRCamera.animations = [];
  88805. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88806. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88807. var animationRotationKeys = [];
  88808. animationRotationKeys.push({
  88809. frame: 0,
  88810. value: this.currentVRCamera.rotationQuaternion
  88811. });
  88812. animationRotationKeys.push({
  88813. frame: 6,
  88814. value: target
  88815. });
  88816. animationRotation.setKeys(animationRotationKeys);
  88817. animationRotation.setEasingFunction(this._circleEase);
  88818. this.currentVRCamera.animations.push(animationRotation);
  88819. this._postProcessMove.animations = [];
  88820. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88821. var vignetteWeightKeys = [];
  88822. vignetteWeightKeys.push({
  88823. frame: 0,
  88824. value: 0
  88825. });
  88826. vignetteWeightKeys.push({
  88827. frame: 3,
  88828. value: 4
  88829. });
  88830. vignetteWeightKeys.push({
  88831. frame: 6,
  88832. value: 0
  88833. });
  88834. animationPP.setKeys(vignetteWeightKeys);
  88835. animationPP.setEasingFunction(this._circleEase);
  88836. this._postProcessMove.animations.push(animationPP);
  88837. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88838. var vignetteStretchKeys = [];
  88839. vignetteStretchKeys.push({
  88840. frame: 0,
  88841. value: 0
  88842. });
  88843. vignetteStretchKeys.push({
  88844. frame: 3,
  88845. value: 10
  88846. });
  88847. vignetteStretchKeys.push({
  88848. frame: 6,
  88849. value: 0
  88850. });
  88851. animationPP2.setKeys(vignetteStretchKeys);
  88852. animationPP2.setEasingFunction(this._circleEase);
  88853. this._postProcessMove.animations.push(animationPP2);
  88854. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88855. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88856. this._postProcessMove.samples = 4;
  88857. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88858. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88859. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88860. });
  88861. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88862. };
  88863. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88864. if (hit.pickedPoint) {
  88865. if (gazer._teleportationRequestInitiated) {
  88866. this._displayTeleportationTarget();
  88867. this._haloCenter.copyFrom(hit.pickedPoint);
  88868. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88869. }
  88870. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88871. if (pickNormal) {
  88872. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88873. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88874. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88875. }
  88876. this._teleportationTarget.position.y += 0.1;
  88877. }
  88878. };
  88879. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88880. var _this = this;
  88881. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88882. return;
  88883. }
  88884. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88885. // offset of the headset from the anchor.
  88886. if (this.webVRCamera.leftCamera) {
  88887. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88888. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88889. location.subtractToRef(this._workingVector, this._workingVector);
  88890. }
  88891. else {
  88892. this._workingVector.copyFrom(location);
  88893. }
  88894. // Add height to account for user's height offset
  88895. if (this.isInVRMode) {
  88896. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88897. }
  88898. else {
  88899. this._workingVector.y += this._defaultHeight;
  88900. }
  88901. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88902. // Create animation from the camera's position to the new location
  88903. this.currentVRCamera.animations = [];
  88904. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88905. var animationCameraTeleportationKeys = [{
  88906. frame: 0,
  88907. value: this.currentVRCamera.position
  88908. },
  88909. {
  88910. frame: 11,
  88911. value: this._workingVector
  88912. }
  88913. ];
  88914. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88915. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88916. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88917. this._postProcessMove.animations = [];
  88918. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88919. var vignetteWeightKeys = [];
  88920. vignetteWeightKeys.push({
  88921. frame: 0,
  88922. value: 0
  88923. });
  88924. vignetteWeightKeys.push({
  88925. frame: 5,
  88926. value: 8
  88927. });
  88928. vignetteWeightKeys.push({
  88929. frame: 11,
  88930. value: 0
  88931. });
  88932. animationPP.setKeys(vignetteWeightKeys);
  88933. this._postProcessMove.animations.push(animationPP);
  88934. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88935. var vignetteStretchKeys = [];
  88936. vignetteStretchKeys.push({
  88937. frame: 0,
  88938. value: 0
  88939. });
  88940. vignetteStretchKeys.push({
  88941. frame: 5,
  88942. value: 10
  88943. });
  88944. vignetteStretchKeys.push({
  88945. frame: 11,
  88946. value: 0
  88947. });
  88948. animationPP2.setKeys(vignetteStretchKeys);
  88949. this._postProcessMove.animations.push(animationPP2);
  88950. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88951. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88952. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88953. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88954. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88955. });
  88956. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88957. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88958. });
  88959. this._hideTeleportationTarget();
  88960. };
  88961. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88962. if (normal) {
  88963. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88964. if (angle < Math.PI / 2) {
  88965. normal.scaleInPlace(-1);
  88966. }
  88967. }
  88968. return normal;
  88969. };
  88970. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88971. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88972. return;
  88973. }
  88974. var ray = gazer._getForwardRay(this._rayLength);
  88975. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88976. // Moving the gazeTracker on the mesh face targetted
  88977. if (hit && hit.pickedPoint) {
  88978. if (this._displayGaze) {
  88979. var multiplier = 1;
  88980. gazer._gazeTracker.isVisible = true;
  88981. if (gazer._isActionableMesh) {
  88982. multiplier = 3;
  88983. }
  88984. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88985. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88986. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88987. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88988. // To avoid z-fighting
  88989. var deltaFighting = 0.002;
  88990. if (pickNormal) {
  88991. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88992. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88993. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88994. }
  88995. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88996. if (gazer._gazeTracker.position.x < 0) {
  88997. gazer._gazeTracker.position.x += deltaFighting;
  88998. }
  88999. else {
  89000. gazer._gazeTracker.position.x -= deltaFighting;
  89001. }
  89002. if (gazer._gazeTracker.position.y < 0) {
  89003. gazer._gazeTracker.position.y += deltaFighting;
  89004. }
  89005. else {
  89006. gazer._gazeTracker.position.y -= deltaFighting;
  89007. }
  89008. if (gazer._gazeTracker.position.z < 0) {
  89009. gazer._gazeTracker.position.z += deltaFighting;
  89010. }
  89011. else {
  89012. gazer._gazeTracker.position.z -= deltaFighting;
  89013. }
  89014. }
  89015. // Changing the size of the laser pointer based on the distance from the targetted point
  89016. gazer._updatePointerDistance(hit.distance);
  89017. }
  89018. else {
  89019. gazer._updatePointerDistance();
  89020. gazer._gazeTracker.isVisible = false;
  89021. }
  89022. if (hit && hit.pickedMesh) {
  89023. gazer._currentHit = hit;
  89024. if (gazer._pointerDownOnMeshAsked) {
  89025. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  89026. }
  89027. // The object selected is the floor, we're in a teleportation scenario
  89028. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89029. // Moving the teleportation area to this targetted point
  89030. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89031. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89032. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89033. }
  89034. gazer._currentMeshSelected = null;
  89035. if (gazer._teleportationRequestInitiated) {
  89036. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89037. }
  89038. return;
  89039. }
  89040. // If not, we're in a selection scenario
  89041. //this._teleportationAllowed = false;
  89042. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89043. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89044. this.onNewMeshPicked.notifyObservers(hit);
  89045. gazer._currentMeshSelected = hit.pickedMesh;
  89046. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89047. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89048. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89049. gazer._isActionableMesh = true;
  89050. }
  89051. else {
  89052. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89053. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89054. gazer._isActionableMesh = false;
  89055. }
  89056. try {
  89057. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89058. }
  89059. catch (err) {
  89060. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89061. }
  89062. }
  89063. else {
  89064. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89065. gazer._currentMeshSelected = null;
  89066. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89067. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89068. }
  89069. }
  89070. }
  89071. else {
  89072. gazer._currentHit = null;
  89073. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89074. gazer._currentMeshSelected = null;
  89075. //this._teleportationAllowed = false;
  89076. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89077. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89078. }
  89079. };
  89080. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89081. if (mesh) {
  89082. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89083. }
  89084. };
  89085. /**
  89086. * Sets the color of the laser ray from the vr controllers.
  89087. * @param color new color for the ray.
  89088. */
  89089. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89090. if (this.leftController) {
  89091. this.leftController._setLaserPointerColor(color);
  89092. }
  89093. if (this.rightController) {
  89094. this.rightController._setLaserPointerColor(color);
  89095. }
  89096. };
  89097. /**
  89098. * Sets the color of the ray from the vr headsets gaze.
  89099. * @param color new color for the ray.
  89100. */
  89101. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89102. if (!this._cameraGazer._gazeTracker.material) {
  89103. return;
  89104. }
  89105. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89106. if (this.leftController) {
  89107. this.leftController._gazeTracker.material.emissiveColor = color;
  89108. }
  89109. if (this.rightController) {
  89110. this.rightController._gazeTracker.material.emissiveColor = color;
  89111. }
  89112. };
  89113. /**
  89114. * Exits VR and disposes of the vr experience helper
  89115. */
  89116. VRExperienceHelper.prototype.dispose = function () {
  89117. if (this.isInVRMode) {
  89118. this.exitVR();
  89119. }
  89120. if (this._postProcessMove) {
  89121. this._postProcessMove.dispose();
  89122. }
  89123. if (this._webVRCamera) {
  89124. this._webVRCamera.dispose();
  89125. }
  89126. if (this._vrDeviceOrientationCamera) {
  89127. this._vrDeviceOrientationCamera.dispose();
  89128. }
  89129. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89130. document.body.removeChild(this._btnVR);
  89131. }
  89132. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89133. this._deviceOrientationCamera.dispose();
  89134. }
  89135. if (this._cameraGazer) {
  89136. this._cameraGazer.dispose();
  89137. }
  89138. if (this.leftController) {
  89139. this.leftController.dispose();
  89140. }
  89141. if (this.rightController) {
  89142. this.rightController.dispose();
  89143. }
  89144. if (this._teleportationTarget) {
  89145. this._teleportationTarget.dispose();
  89146. }
  89147. this._floorMeshesCollection = [];
  89148. document.removeEventListener("keydown", this._onKeyDown);
  89149. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89150. window.removeEventListener("resize", this._onResize);
  89151. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89152. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89153. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89154. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89155. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89156. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89157. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89158. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89159. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89160. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89161. this._scene.unregisterBeforeRender(this.beforeRender);
  89162. };
  89163. /**
  89164. * Gets the name of the VRExperienceHelper class
  89165. * @returns "VRExperienceHelper"
  89166. */
  89167. VRExperienceHelper.prototype.getClassName = function () {
  89168. return "VRExperienceHelper";
  89169. };
  89170. return VRExperienceHelper;
  89171. }());
  89172. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89173. })(BABYLON || (BABYLON = {}));
  89174. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89175. // Mainly based on these 2 articles :
  89176. // 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
  89177. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89178. var BABYLON;
  89179. (function (BABYLON) {
  89180. /**
  89181. * Defines the potential axis of a Joystick
  89182. */
  89183. var JoystickAxis;
  89184. (function (JoystickAxis) {
  89185. /** X axis */
  89186. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89187. /** Y axis */
  89188. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89189. /** Z axis */
  89190. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89191. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89192. /**
  89193. * Class used to define virtual joystick (used in touch mode)
  89194. */
  89195. var VirtualJoystick = /** @class */ (function () {
  89196. /**
  89197. * Creates a new virtual joystick
  89198. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89199. */
  89200. function VirtualJoystick(leftJoystick) {
  89201. var _this = this;
  89202. if (leftJoystick) {
  89203. this._leftJoystick = true;
  89204. }
  89205. else {
  89206. this._leftJoystick = false;
  89207. }
  89208. VirtualJoystick._globalJoystickIndex++;
  89209. // By default left & right arrow keys are moving the X
  89210. // and up & down keys are moving the Y
  89211. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89212. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89213. this.reverseLeftRight = false;
  89214. this.reverseUpDown = false;
  89215. // collections of pointers
  89216. this._touches = new BABYLON.StringDictionary();
  89217. this.deltaPosition = BABYLON.Vector3.Zero();
  89218. this._joystickSensibility = 25;
  89219. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89220. this._onResize = function (evt) {
  89221. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89222. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89223. if (VirtualJoystick.vjCanvas) {
  89224. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89225. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89226. }
  89227. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89228. };
  89229. // injecting a canvas element on top of the canvas 3D game
  89230. if (!VirtualJoystick.vjCanvas) {
  89231. window.addEventListener("resize", this._onResize, false);
  89232. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89233. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89234. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89235. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89236. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89237. VirtualJoystick.vjCanvas.style.width = "100%";
  89238. VirtualJoystick.vjCanvas.style.height = "100%";
  89239. VirtualJoystick.vjCanvas.style.position = "absolute";
  89240. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89241. VirtualJoystick.vjCanvas.style.top = "0px";
  89242. VirtualJoystick.vjCanvas.style.left = "0px";
  89243. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89244. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89245. // Support for jQuery PEP polyfill
  89246. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89247. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89248. if (!context) {
  89249. throw new Error("Unable to create canvas for virtual joystick");
  89250. }
  89251. VirtualJoystick.vjCanvasContext = context;
  89252. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89253. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89254. document.body.appendChild(VirtualJoystick.vjCanvas);
  89255. }
  89256. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89257. this.pressed = false;
  89258. // default joystick color
  89259. this._joystickColor = "cyan";
  89260. this._joystickPointerID = -1;
  89261. // current joystick position
  89262. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89263. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89264. // origin joystick position
  89265. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89266. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89267. this._onPointerDownHandlerRef = function (evt) {
  89268. _this._onPointerDown(evt);
  89269. };
  89270. this._onPointerMoveHandlerRef = function (evt) {
  89271. _this._onPointerMove(evt);
  89272. };
  89273. this._onPointerUpHandlerRef = function (evt) {
  89274. _this._onPointerUp(evt);
  89275. };
  89276. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89277. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89278. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89279. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89280. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89281. evt.preventDefault(); // Disables system menu
  89282. }, false);
  89283. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89284. }
  89285. /**
  89286. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89287. * @param newJoystickSensibility defines the new sensibility
  89288. */
  89289. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89290. this._joystickSensibility = newJoystickSensibility;
  89291. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89292. };
  89293. VirtualJoystick.prototype._onPointerDown = function (e) {
  89294. var positionOnScreenCondition;
  89295. e.preventDefault();
  89296. if (this._leftJoystick === true) {
  89297. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89298. }
  89299. else {
  89300. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89301. }
  89302. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89303. // First contact will be dedicated to the virtual joystick
  89304. this._joystickPointerID = e.pointerId;
  89305. this._joystickPointerStartPos.x = e.clientX;
  89306. this._joystickPointerStartPos.y = e.clientY;
  89307. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89308. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89309. this._deltaJoystickVector.x = 0;
  89310. this._deltaJoystickVector.y = 0;
  89311. this.pressed = true;
  89312. this._touches.add(e.pointerId.toString(), e);
  89313. }
  89314. else {
  89315. // You can only trigger the action buttons with a joystick declared
  89316. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89317. this._action();
  89318. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89319. }
  89320. }
  89321. };
  89322. VirtualJoystick.prototype._onPointerMove = function (e) {
  89323. // If the current pointer is the one associated to the joystick (first touch contact)
  89324. if (this._joystickPointerID == e.pointerId) {
  89325. this._joystickPointerPos.x = e.clientX;
  89326. this._joystickPointerPos.y = e.clientY;
  89327. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89328. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89329. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89330. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89331. switch (this._axisTargetedByLeftAndRight) {
  89332. case JoystickAxis.X:
  89333. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89334. break;
  89335. case JoystickAxis.Y:
  89336. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89337. break;
  89338. case JoystickAxis.Z:
  89339. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89340. break;
  89341. }
  89342. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89343. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89344. switch (this._axisTargetedByUpAndDown) {
  89345. case JoystickAxis.X:
  89346. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89347. break;
  89348. case JoystickAxis.Y:
  89349. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89350. break;
  89351. case JoystickAxis.Z:
  89352. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89353. break;
  89354. }
  89355. }
  89356. else {
  89357. var data = this._touches.get(e.pointerId.toString());
  89358. if (data) {
  89359. data.x = e.clientX;
  89360. data.y = e.clientY;
  89361. }
  89362. }
  89363. };
  89364. VirtualJoystick.prototype._onPointerUp = function (e) {
  89365. if (this._joystickPointerID == e.pointerId) {
  89366. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89367. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89368. this._joystickPointerID = -1;
  89369. this.pressed = false;
  89370. }
  89371. else {
  89372. var touch = this._touches.get(e.pointerId.toString());
  89373. if (touch) {
  89374. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89375. }
  89376. }
  89377. this._deltaJoystickVector.x = 0;
  89378. this._deltaJoystickVector.y = 0;
  89379. this._touches.remove(e.pointerId.toString());
  89380. };
  89381. /**
  89382. * Change the color of the virtual joystick
  89383. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89384. */
  89385. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89386. this._joystickColor = newColor;
  89387. };
  89388. /**
  89389. * Defines a callback to call when the joystick is touched
  89390. * @param action defines the callback
  89391. */
  89392. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89393. this._action = action;
  89394. };
  89395. /**
  89396. * Defines which axis you'd like to control for left & right
  89397. * @param axis defines the axis to use
  89398. */
  89399. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89400. switch (axis) {
  89401. case JoystickAxis.X:
  89402. case JoystickAxis.Y:
  89403. case JoystickAxis.Z:
  89404. this._axisTargetedByLeftAndRight = axis;
  89405. break;
  89406. default:
  89407. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89408. break;
  89409. }
  89410. };
  89411. /**
  89412. * Defines which axis you'd like to control for up & down
  89413. * @param axis defines the axis to use
  89414. */
  89415. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89416. switch (axis) {
  89417. case JoystickAxis.X:
  89418. case JoystickAxis.Y:
  89419. case JoystickAxis.Z:
  89420. this._axisTargetedByUpAndDown = axis;
  89421. break;
  89422. default:
  89423. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89424. break;
  89425. }
  89426. };
  89427. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89428. var _this = this;
  89429. if (this.pressed) {
  89430. this._touches.forEach(function (key, touch) {
  89431. if (touch.pointerId === _this._joystickPointerID) {
  89432. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89433. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89434. VirtualJoystick.vjCanvasContext.beginPath();
  89435. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89436. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89437. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89438. VirtualJoystick.vjCanvasContext.stroke();
  89439. VirtualJoystick.vjCanvasContext.closePath();
  89440. VirtualJoystick.vjCanvasContext.beginPath();
  89441. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89442. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89443. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89444. VirtualJoystick.vjCanvasContext.stroke();
  89445. VirtualJoystick.vjCanvasContext.closePath();
  89446. VirtualJoystick.vjCanvasContext.beginPath();
  89447. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89448. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89449. VirtualJoystick.vjCanvasContext.stroke();
  89450. VirtualJoystick.vjCanvasContext.closePath();
  89451. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89452. }
  89453. else {
  89454. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89455. VirtualJoystick.vjCanvasContext.beginPath();
  89456. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89457. VirtualJoystick.vjCanvasContext.beginPath();
  89458. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89459. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89460. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89461. VirtualJoystick.vjCanvasContext.stroke();
  89462. VirtualJoystick.vjCanvasContext.closePath();
  89463. touch.prevX = touch.x;
  89464. touch.prevY = touch.y;
  89465. }
  89466. ;
  89467. });
  89468. }
  89469. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89470. };
  89471. /**
  89472. * Release internal HTML canvas
  89473. */
  89474. VirtualJoystick.prototype.releaseCanvas = function () {
  89475. if (VirtualJoystick.vjCanvas) {
  89476. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89477. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89478. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89479. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89480. window.removeEventListener("resize", this._onResize);
  89481. document.body.removeChild(VirtualJoystick.vjCanvas);
  89482. VirtualJoystick.vjCanvas = null;
  89483. }
  89484. };
  89485. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89486. VirtualJoystick._globalJoystickIndex = 0;
  89487. return VirtualJoystick;
  89488. }());
  89489. BABYLON.VirtualJoystick = VirtualJoystick;
  89490. })(BABYLON || (BABYLON = {}));
  89491. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89492. var BABYLON;
  89493. (function (BABYLON) {
  89494. // We're mainly based on the logic defined into the FreeCamera code
  89495. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89496. __extends(VirtualJoysticksCamera, _super);
  89497. function VirtualJoysticksCamera(name, position, scene) {
  89498. var _this = _super.call(this, name, position, scene) || this;
  89499. _this.inputs.addVirtualJoystick();
  89500. return _this;
  89501. }
  89502. VirtualJoysticksCamera.prototype.getClassName = function () {
  89503. return "VirtualJoysticksCamera";
  89504. };
  89505. return VirtualJoysticksCamera;
  89506. }(BABYLON.FreeCamera));
  89507. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89508. })(BABYLON || (BABYLON = {}));
  89509. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89510. var BABYLON;
  89511. (function (BABYLON) {
  89512. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89513. function FreeCameraVirtualJoystickInput() {
  89514. }
  89515. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89516. return this._leftjoystick;
  89517. };
  89518. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89519. return this._rightjoystick;
  89520. };
  89521. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89522. if (this._leftjoystick) {
  89523. var camera = this.camera;
  89524. var speed = camera._computeLocalCameraSpeed() * 50;
  89525. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89526. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89527. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89528. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89529. if (!this._leftjoystick.pressed) {
  89530. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89531. }
  89532. if (!this._rightjoystick.pressed) {
  89533. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89534. }
  89535. }
  89536. };
  89537. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89538. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89539. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89540. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89541. this._leftjoystick.setJoystickSensibility(0.15);
  89542. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89543. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89544. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89545. this._rightjoystick.reverseUpDown = true;
  89546. this._rightjoystick.setJoystickSensibility(0.05);
  89547. this._rightjoystick.setJoystickColor("yellow");
  89548. };
  89549. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89550. this._leftjoystick.releaseCanvas();
  89551. this._rightjoystick.releaseCanvas();
  89552. };
  89553. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89554. return "FreeCameraVirtualJoystickInput";
  89555. };
  89556. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89557. return "virtualJoystick";
  89558. };
  89559. return FreeCameraVirtualJoystickInput;
  89560. }());
  89561. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89562. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89563. })(BABYLON || (BABYLON = {}));
  89564. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89565. var BABYLON;
  89566. (function (BABYLON) {
  89567. var SimplificationSettings = /** @class */ (function () {
  89568. function SimplificationSettings(quality, distance, optimizeMesh) {
  89569. this.quality = quality;
  89570. this.distance = distance;
  89571. this.optimizeMesh = optimizeMesh;
  89572. }
  89573. return SimplificationSettings;
  89574. }());
  89575. BABYLON.SimplificationSettings = SimplificationSettings;
  89576. var SimplificationQueue = /** @class */ (function () {
  89577. function SimplificationQueue() {
  89578. this.running = false;
  89579. this._simplificationArray = [];
  89580. }
  89581. SimplificationQueue.prototype.addTask = function (task) {
  89582. this._simplificationArray.push(task);
  89583. };
  89584. SimplificationQueue.prototype.executeNext = function () {
  89585. var task = this._simplificationArray.pop();
  89586. if (task) {
  89587. this.running = true;
  89588. this.runSimplification(task);
  89589. }
  89590. else {
  89591. this.running = false;
  89592. }
  89593. };
  89594. SimplificationQueue.prototype.runSimplification = function (task) {
  89595. var _this = this;
  89596. if (task.parallelProcessing) {
  89597. //parallel simplifier
  89598. task.settings.forEach(function (setting) {
  89599. var simplifier = _this.getSimplifier(task);
  89600. simplifier.simplify(setting, function (newMesh) {
  89601. task.mesh.addLODLevel(setting.distance, newMesh);
  89602. newMesh.isVisible = true;
  89603. //check if it is the last
  89604. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89605. //all done, run the success callback.
  89606. task.successCallback();
  89607. }
  89608. _this.executeNext();
  89609. });
  89610. });
  89611. }
  89612. else {
  89613. //single simplifier.
  89614. var simplifier = this.getSimplifier(task);
  89615. var runDecimation = function (setting, callback) {
  89616. simplifier.simplify(setting, function (newMesh) {
  89617. task.mesh.addLODLevel(setting.distance, newMesh);
  89618. newMesh.isVisible = true;
  89619. //run the next quality level
  89620. callback();
  89621. });
  89622. };
  89623. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89624. runDecimation(task.settings[loop.index], function () {
  89625. loop.executeNext();
  89626. });
  89627. }, function () {
  89628. //execution ended, run the success callback.
  89629. if (task.successCallback) {
  89630. task.successCallback();
  89631. }
  89632. _this.executeNext();
  89633. });
  89634. }
  89635. };
  89636. SimplificationQueue.prototype.getSimplifier = function (task) {
  89637. switch (task.simplificationType) {
  89638. case SimplificationType.QUADRATIC:
  89639. default:
  89640. return new QuadraticErrorSimplification(task.mesh);
  89641. }
  89642. };
  89643. return SimplificationQueue;
  89644. }());
  89645. BABYLON.SimplificationQueue = SimplificationQueue;
  89646. /**
  89647. * The implemented types of simplification
  89648. * At the moment only Quadratic Error Decimation is implemented
  89649. */
  89650. var SimplificationType;
  89651. (function (SimplificationType) {
  89652. /** Quadratic error decimation */
  89653. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89654. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89655. var DecimationTriangle = /** @class */ (function () {
  89656. function DecimationTriangle(vertices) {
  89657. this.vertices = vertices;
  89658. this.error = new Array(4);
  89659. this.deleted = false;
  89660. this.isDirty = false;
  89661. this.deletePending = false;
  89662. this.borderFactor = 0;
  89663. }
  89664. return DecimationTriangle;
  89665. }());
  89666. BABYLON.DecimationTriangle = DecimationTriangle;
  89667. var DecimationVertex = /** @class */ (function () {
  89668. function DecimationVertex(position, id) {
  89669. this.position = position;
  89670. this.id = id;
  89671. this.isBorder = true;
  89672. this.q = new QuadraticMatrix();
  89673. this.triangleCount = 0;
  89674. this.triangleStart = 0;
  89675. this.originalOffsets = [];
  89676. }
  89677. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89678. this.position.copyFrom(newPosition);
  89679. };
  89680. return DecimationVertex;
  89681. }());
  89682. BABYLON.DecimationVertex = DecimationVertex;
  89683. var QuadraticMatrix = /** @class */ (function () {
  89684. function QuadraticMatrix(data) {
  89685. this.data = new Array(10);
  89686. for (var i = 0; i < 10; ++i) {
  89687. if (data && data[i]) {
  89688. this.data[i] = data[i];
  89689. }
  89690. else {
  89691. this.data[i] = 0;
  89692. }
  89693. }
  89694. }
  89695. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89696. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89697. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89698. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89699. return det;
  89700. };
  89701. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89702. for (var i = 0; i < 10; ++i) {
  89703. this.data[i] += matrix.data[i];
  89704. }
  89705. };
  89706. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89707. for (var i = 0; i < 10; ++i) {
  89708. this.data[i] += data[i];
  89709. }
  89710. };
  89711. QuadraticMatrix.prototype.add = function (matrix) {
  89712. var m = new QuadraticMatrix();
  89713. for (var i = 0; i < 10; ++i) {
  89714. m.data[i] = this.data[i] + matrix.data[i];
  89715. }
  89716. return m;
  89717. };
  89718. QuadraticMatrix.FromData = function (a, b, c, d) {
  89719. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89720. };
  89721. //returning an array to avoid garbage collection
  89722. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89723. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89724. };
  89725. return QuadraticMatrix;
  89726. }());
  89727. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89728. var Reference = /** @class */ (function () {
  89729. function Reference(vertexId, triangleId) {
  89730. this.vertexId = vertexId;
  89731. this.triangleId = triangleId;
  89732. }
  89733. return Reference;
  89734. }());
  89735. BABYLON.Reference = Reference;
  89736. /**
  89737. * An implementation of the Quadratic Error simplification algorithm.
  89738. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89739. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89740. * @author RaananW
  89741. */
  89742. var QuadraticErrorSimplification = /** @class */ (function () {
  89743. function QuadraticErrorSimplification(_mesh) {
  89744. this._mesh = _mesh;
  89745. this.syncIterations = 5000;
  89746. this.aggressiveness = 7;
  89747. this.decimationIterations = 100;
  89748. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89749. }
  89750. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89751. var _this = this;
  89752. this.initDecimatedMesh();
  89753. //iterating through the submeshes array, one after the other.
  89754. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89755. _this.initWithMesh(loop.index, function () {
  89756. _this.runDecimation(settings, loop.index, function () {
  89757. loop.executeNext();
  89758. });
  89759. }, settings.optimizeMesh);
  89760. }, function () {
  89761. setTimeout(function () {
  89762. successCallback(_this._reconstructedMesh);
  89763. }, 0);
  89764. });
  89765. };
  89766. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89767. var _this = this;
  89768. var targetCount = ~~(this.triangles.length * settings.quality);
  89769. var deletedTriangles = 0;
  89770. var triangleCount = this.triangles.length;
  89771. var iterationFunction = function (iteration, callback) {
  89772. setTimeout(function () {
  89773. if (iteration % 5 === 0) {
  89774. _this.updateMesh(iteration === 0);
  89775. }
  89776. for (var i = 0; i < _this.triangles.length; ++i) {
  89777. _this.triangles[i].isDirty = false;
  89778. }
  89779. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89780. var trianglesIterator = function (i) {
  89781. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89782. var t = _this.triangles[tIdx];
  89783. if (!t)
  89784. return;
  89785. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89786. return;
  89787. }
  89788. for (var j = 0; j < 3; ++j) {
  89789. if (t.error[j] < threshold) {
  89790. var deleted0 = [];
  89791. var deleted1 = [];
  89792. var v0 = t.vertices[j];
  89793. var v1 = t.vertices[(j + 1) % 3];
  89794. if (v0.isBorder || v1.isBorder)
  89795. continue;
  89796. var p = BABYLON.Vector3.Zero();
  89797. var n = BABYLON.Vector3.Zero();
  89798. var uv = BABYLON.Vector2.Zero();
  89799. var color = new BABYLON.Color4(0, 0, 0, 1);
  89800. _this.calculateError(v0, v1, p, n, uv, color);
  89801. var delTr = new Array();
  89802. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89803. continue;
  89804. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89805. continue;
  89806. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89807. continue;
  89808. var uniqueArray = new Array();
  89809. delTr.forEach(function (deletedT) {
  89810. if (uniqueArray.indexOf(deletedT) === -1) {
  89811. deletedT.deletePending = true;
  89812. uniqueArray.push(deletedT);
  89813. }
  89814. });
  89815. if (uniqueArray.length % 2 !== 0) {
  89816. continue;
  89817. }
  89818. v0.q = v1.q.add(v0.q);
  89819. v0.updatePosition(p);
  89820. var tStart = _this.references.length;
  89821. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89822. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89823. var tCount = _this.references.length - tStart;
  89824. if (tCount <= v0.triangleCount) {
  89825. if (tCount) {
  89826. for (var c = 0; c < tCount; c++) {
  89827. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89828. }
  89829. }
  89830. }
  89831. else {
  89832. v0.triangleStart = tStart;
  89833. }
  89834. v0.triangleCount = tCount;
  89835. break;
  89836. }
  89837. }
  89838. };
  89839. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89840. }, 0);
  89841. };
  89842. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89843. if (triangleCount - deletedTriangles <= targetCount)
  89844. loop.breakLoop();
  89845. else {
  89846. iterationFunction(loop.index, function () {
  89847. loop.executeNext();
  89848. });
  89849. }
  89850. }, function () {
  89851. setTimeout(function () {
  89852. //reconstruct this part of the mesh
  89853. _this.reconstructMesh(submeshIndex);
  89854. successCallback();
  89855. }, 0);
  89856. });
  89857. };
  89858. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89859. var _this = this;
  89860. this.vertices = [];
  89861. this.triangles = [];
  89862. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89863. var indices = this._mesh.getIndices();
  89864. var submesh = this._mesh.subMeshes[submeshIndex];
  89865. var findInVertices = function (positionToSearch) {
  89866. if (optimizeMesh) {
  89867. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89868. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89869. return _this.vertices[ii];
  89870. }
  89871. }
  89872. }
  89873. return null;
  89874. };
  89875. var vertexReferences = [];
  89876. var vertexInit = function (i) {
  89877. if (!positionData) {
  89878. return;
  89879. }
  89880. var offset = i + submesh.verticesStart;
  89881. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89882. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89883. vertex.originalOffsets.push(offset);
  89884. if (vertex.id === _this.vertices.length) {
  89885. _this.vertices.push(vertex);
  89886. }
  89887. vertexReferences.push(vertex.id);
  89888. };
  89889. //var totalVertices = mesh.getTotalVertices();
  89890. var totalVertices = submesh.verticesCount;
  89891. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89892. var indicesInit = function (i) {
  89893. if (!indices) {
  89894. return;
  89895. }
  89896. var offset = (submesh.indexStart / 3) + i;
  89897. var pos = (offset * 3);
  89898. var i0 = indices[pos + 0];
  89899. var i1 = indices[pos + 1];
  89900. var i2 = indices[pos + 2];
  89901. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89902. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89903. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89904. var triangle = new DecimationTriangle([v0, v1, v2]);
  89905. triangle.originalOffset = pos;
  89906. _this.triangles.push(triangle);
  89907. };
  89908. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89909. _this.init(callback);
  89910. });
  89911. });
  89912. };
  89913. QuadraticErrorSimplification.prototype.init = function (callback) {
  89914. var _this = this;
  89915. var triangleInit1 = function (i) {
  89916. var t = _this.triangles[i];
  89917. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89918. for (var j = 0; j < 3; j++) {
  89919. 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))));
  89920. }
  89921. };
  89922. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89923. var triangleInit2 = function (i) {
  89924. var t = _this.triangles[i];
  89925. for (var j = 0; j < 3; ++j) {
  89926. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89927. }
  89928. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89929. };
  89930. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89931. callback();
  89932. });
  89933. });
  89934. };
  89935. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89936. var newTriangles = [];
  89937. var i;
  89938. for (i = 0; i < this.vertices.length; ++i) {
  89939. this.vertices[i].triangleCount = 0;
  89940. }
  89941. var t;
  89942. var j;
  89943. for (i = 0; i < this.triangles.length; ++i) {
  89944. if (!this.triangles[i].deleted) {
  89945. t = this.triangles[i];
  89946. for (j = 0; j < 3; ++j) {
  89947. t.vertices[j].triangleCount = 1;
  89948. }
  89949. newTriangles.push(t);
  89950. }
  89951. }
  89952. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89953. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89954. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89955. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89956. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89957. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89958. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89959. var vertexCount = 0;
  89960. for (i = 0; i < this.vertices.length; ++i) {
  89961. var vertex = this.vertices[i];
  89962. vertex.id = vertexCount;
  89963. if (vertex.triangleCount) {
  89964. vertex.originalOffsets.forEach(function (originalOffset) {
  89965. if (!normalData) {
  89966. return;
  89967. }
  89968. newPositionData.push(vertex.position.x);
  89969. newPositionData.push(vertex.position.y);
  89970. newPositionData.push(vertex.position.z);
  89971. newNormalData.push(normalData[originalOffset * 3]);
  89972. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89973. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89974. if (uvs && uvs.length) {
  89975. newUVsData.push(uvs[(originalOffset * 2)]);
  89976. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89977. }
  89978. else if (colorsData && colorsData.length) {
  89979. newColorsData.push(colorsData[(originalOffset * 4)]);
  89980. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89981. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89982. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89983. }
  89984. ++vertexCount;
  89985. });
  89986. }
  89987. }
  89988. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89989. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89990. var submeshesArray = this._reconstructedMesh.subMeshes;
  89991. this._reconstructedMesh.subMeshes = [];
  89992. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89993. var originalIndices = this._mesh.getIndices();
  89994. for (i = 0; i < newTriangles.length; ++i) {
  89995. t = newTriangles[i]; //now get the new referencing point for each vertex
  89996. [0, 1, 2].forEach(function (idx) {
  89997. var id = originalIndices[t.originalOffset + idx];
  89998. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89999. if (offset < 0)
  90000. offset = 0;
  90001. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90002. });
  90003. }
  90004. //overwriting the old vertex buffers and indices.
  90005. this._reconstructedMesh.setIndices(newIndicesArray);
  90006. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90007. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90008. if (newUVsData.length > 0)
  90009. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90010. if (newColorsData.length > 0)
  90011. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90012. //create submesh
  90013. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90014. if (submeshIndex > 0) {
  90015. this._reconstructedMesh.subMeshes = [];
  90016. submeshesArray.forEach(function (submesh) {
  90017. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90018. });
  90019. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90020. }
  90021. };
  90022. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90023. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90024. this._reconstructedMesh.material = this._mesh.material;
  90025. this._reconstructedMesh.parent = this._mesh.parent;
  90026. this._reconstructedMesh.isVisible = false;
  90027. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90028. };
  90029. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90030. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90031. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90032. if (t.deleted)
  90033. continue;
  90034. var s = this.references[vertex1.triangleStart + i].vertexId;
  90035. var v1 = t.vertices[(s + 1) % 3];
  90036. var v2 = t.vertices[(s + 2) % 3];
  90037. if ((v1 === vertex2 || v2 === vertex2)) {
  90038. deletedArray[i] = true;
  90039. delTr.push(t);
  90040. continue;
  90041. }
  90042. var d1 = v1.position.subtract(point);
  90043. d1 = d1.normalize();
  90044. var d2 = v2.position.subtract(point);
  90045. d2 = d2.normalize();
  90046. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90047. return true;
  90048. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90049. deletedArray[i] = false;
  90050. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90051. return true;
  90052. }
  90053. return false;
  90054. };
  90055. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90056. var newDeleted = deletedTriangles;
  90057. for (var i = 0; i < vertex.triangleCount; ++i) {
  90058. var ref = this.references[vertex.triangleStart + i];
  90059. var t = this.triangles[ref.triangleId];
  90060. if (t.deleted)
  90061. continue;
  90062. if (deletedArray[i] && t.deletePending) {
  90063. t.deleted = true;
  90064. newDeleted++;
  90065. continue;
  90066. }
  90067. t.vertices[ref.vertexId] = origVertex;
  90068. t.isDirty = true;
  90069. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90070. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90071. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90072. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90073. this.references.push(ref);
  90074. }
  90075. return newDeleted;
  90076. };
  90077. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90078. for (var i = 0; i < this.vertices.length; ++i) {
  90079. var vCount = [];
  90080. var vId = [];
  90081. var v = this.vertices[i];
  90082. var j;
  90083. for (j = 0; j < v.triangleCount; ++j) {
  90084. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90085. for (var ii = 0; ii < 3; ii++) {
  90086. var ofs = 0;
  90087. var vv = triangle.vertices[ii];
  90088. while (ofs < vCount.length) {
  90089. if (vId[ofs] === vv.id)
  90090. break;
  90091. ++ofs;
  90092. }
  90093. if (ofs === vCount.length) {
  90094. vCount.push(1);
  90095. vId.push(vv.id);
  90096. }
  90097. else {
  90098. vCount[ofs]++;
  90099. }
  90100. }
  90101. }
  90102. for (j = 0; j < vCount.length; ++j) {
  90103. if (vCount[j] === 1) {
  90104. this.vertices[vId[j]].isBorder = true;
  90105. }
  90106. else {
  90107. this.vertices[vId[j]].isBorder = false;
  90108. }
  90109. }
  90110. }
  90111. };
  90112. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90113. if (identifyBorders === void 0) { identifyBorders = false; }
  90114. var i;
  90115. if (!identifyBorders) {
  90116. var newTrianglesVector = [];
  90117. for (i = 0; i < this.triangles.length; ++i) {
  90118. if (!this.triangles[i].deleted) {
  90119. newTrianglesVector.push(this.triangles[i]);
  90120. }
  90121. }
  90122. this.triangles = newTrianglesVector;
  90123. }
  90124. for (i = 0; i < this.vertices.length; ++i) {
  90125. this.vertices[i].triangleCount = 0;
  90126. this.vertices[i].triangleStart = 0;
  90127. }
  90128. var t;
  90129. var j;
  90130. var v;
  90131. for (i = 0; i < this.triangles.length; ++i) {
  90132. t = this.triangles[i];
  90133. for (j = 0; j < 3; ++j) {
  90134. v = t.vertices[j];
  90135. v.triangleCount++;
  90136. }
  90137. }
  90138. var tStart = 0;
  90139. for (i = 0; i < this.vertices.length; ++i) {
  90140. this.vertices[i].triangleStart = tStart;
  90141. tStart += this.vertices[i].triangleCount;
  90142. this.vertices[i].triangleCount = 0;
  90143. }
  90144. var newReferences = new Array(this.triangles.length * 3);
  90145. for (i = 0; i < this.triangles.length; ++i) {
  90146. t = this.triangles[i];
  90147. for (j = 0; j < 3; ++j) {
  90148. v = t.vertices[j];
  90149. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90150. v.triangleCount++;
  90151. }
  90152. }
  90153. this.references = newReferences;
  90154. if (identifyBorders) {
  90155. this.identifyBorder();
  90156. }
  90157. };
  90158. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90159. var x = point.x;
  90160. var y = point.y;
  90161. var z = point.z;
  90162. 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
  90163. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90164. };
  90165. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90166. var q = vertex1.q.add(vertex2.q);
  90167. var border = vertex1.isBorder && vertex2.isBorder;
  90168. var error = 0;
  90169. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90170. if (qDet !== 0 && !border) {
  90171. if (!pointResult) {
  90172. pointResult = BABYLON.Vector3.Zero();
  90173. }
  90174. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90175. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90176. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90177. error = this.vertexError(q, pointResult);
  90178. }
  90179. else {
  90180. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90181. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90182. var error1 = this.vertexError(q, vertex1.position);
  90183. var error2 = this.vertexError(q, vertex2.position);
  90184. var error3 = this.vertexError(q, p3);
  90185. error = Math.min(error1, error2, error3);
  90186. if (error === error1) {
  90187. if (pointResult) {
  90188. pointResult.copyFrom(vertex1.position);
  90189. }
  90190. }
  90191. else if (error === error2) {
  90192. if (pointResult) {
  90193. pointResult.copyFrom(vertex2.position);
  90194. }
  90195. }
  90196. else {
  90197. if (pointResult) {
  90198. pointResult.copyFrom(p3);
  90199. }
  90200. }
  90201. }
  90202. return error;
  90203. };
  90204. return QuadraticErrorSimplification;
  90205. }());
  90206. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90207. })(BABYLON || (BABYLON = {}));
  90208. //# sourceMappingURL=babylon.meshSimplification.js.map
  90209. var BABYLON;
  90210. (function (BABYLON) {
  90211. var MeshLODLevel = /** @class */ (function () {
  90212. function MeshLODLevel(distance, mesh) {
  90213. this.distance = distance;
  90214. this.mesh = mesh;
  90215. }
  90216. return MeshLODLevel;
  90217. }());
  90218. BABYLON.MeshLODLevel = MeshLODLevel;
  90219. })(BABYLON || (BABYLON = {}));
  90220. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90221. var BABYLON;
  90222. (function (BABYLON) {
  90223. /**
  90224. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90225. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90226. */
  90227. var SceneOptimization = /** @class */ (function () {
  90228. /**
  90229. * Creates the SceneOptimization object
  90230. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90231. * @param desc defines the description associated with the optimization
  90232. */
  90233. function SceneOptimization(
  90234. /**
  90235. * Defines the priority of this optimization (0 by default which means first in the list)
  90236. */
  90237. priority) {
  90238. if (priority === void 0) { priority = 0; }
  90239. this.priority = priority;
  90240. }
  90241. /**
  90242. * Gets a string describing the action executed by the current optimization
  90243. * @returns description string
  90244. */
  90245. SceneOptimization.prototype.getDescription = function () {
  90246. return "";
  90247. };
  90248. /**
  90249. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90250. * @param scene defines the current scene where to apply this optimization
  90251. * @param optimizer defines the current optimizer
  90252. * @returns true if everything that can be done was applied
  90253. */
  90254. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90255. return true;
  90256. };
  90257. ;
  90258. return SceneOptimization;
  90259. }());
  90260. BABYLON.SceneOptimization = SceneOptimization;
  90261. /**
  90262. * Defines an optimization used to reduce the size of render target textures
  90263. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90264. */
  90265. var TextureOptimization = /** @class */ (function (_super) {
  90266. __extends(TextureOptimization, _super);
  90267. /**
  90268. * Creates the TextureOptimization object
  90269. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90270. * @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
  90271. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90272. */
  90273. function TextureOptimization(
  90274. /**
  90275. * Defines the priority of this optimization (0 by default which means first in the list)
  90276. */
  90277. priority,
  90278. /**
  90279. * 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
  90280. */
  90281. maximumSize,
  90282. /**
  90283. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90284. */
  90285. step) {
  90286. if (priority === void 0) { priority = 0; }
  90287. if (maximumSize === void 0) { maximumSize = 1024; }
  90288. if (step === void 0) { step = 0.5; }
  90289. var _this = _super.call(this, priority) || this;
  90290. _this.priority = priority;
  90291. _this.maximumSize = maximumSize;
  90292. _this.step = step;
  90293. return _this;
  90294. }
  90295. /**
  90296. * Gets a string describing the action executed by the current optimization
  90297. * @returns description string
  90298. */
  90299. TextureOptimization.prototype.getDescription = function () {
  90300. return "Reducing render target texture size to " + this.maximumSize;
  90301. };
  90302. /**
  90303. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90304. * @param scene defines the current scene where to apply this optimization
  90305. * @param optimizer defines the current optimizer
  90306. * @returns true if everything that can be done was applied
  90307. */
  90308. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90309. var allDone = true;
  90310. for (var index = 0; index < scene.textures.length; index++) {
  90311. var texture = scene.textures[index];
  90312. if (!texture.canRescale || texture.getContext) {
  90313. continue;
  90314. }
  90315. var currentSize = texture.getSize();
  90316. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90317. if (maxDimension > this.maximumSize) {
  90318. texture.scale(this.step);
  90319. allDone = false;
  90320. }
  90321. }
  90322. return allDone;
  90323. };
  90324. return TextureOptimization;
  90325. }(SceneOptimization));
  90326. BABYLON.TextureOptimization = TextureOptimization;
  90327. /**
  90328. * Defines an optimization used to increase or decrease the rendering resolution
  90329. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90330. */
  90331. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90332. __extends(HardwareScalingOptimization, _super);
  90333. /**
  90334. * Creates the HardwareScalingOptimization object
  90335. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90336. * @param maximumScale defines the maximum scale to use (2 by default)
  90337. * @param step defines the step to use between two passes (0.5 by default)
  90338. */
  90339. function HardwareScalingOptimization(
  90340. /**
  90341. * Defines the priority of this optimization (0 by default which means first in the list)
  90342. */
  90343. priority,
  90344. /**
  90345. * Defines the maximum scale to use (2 by default)
  90346. */
  90347. maximumScale,
  90348. /**
  90349. * Defines the step to use between two passes (0.5 by default)
  90350. */
  90351. step) {
  90352. if (priority === void 0) { priority = 0; }
  90353. if (maximumScale === void 0) { maximumScale = 2; }
  90354. if (step === void 0) { step = 0.25; }
  90355. var _this = _super.call(this, priority) || this;
  90356. _this.priority = priority;
  90357. _this.maximumScale = maximumScale;
  90358. _this.step = step;
  90359. _this._currentScale = -1;
  90360. _this._directionOffset = 1;
  90361. return _this;
  90362. }
  90363. /**
  90364. * Gets a string describing the action executed by the current optimization
  90365. * @return description string
  90366. */
  90367. HardwareScalingOptimization.prototype.getDescription = function () {
  90368. return "Setting hardware scaling level to " + this._currentScale;
  90369. };
  90370. /**
  90371. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90372. * @param scene defines the current scene where to apply this optimization
  90373. * @param optimizer defines the current optimizer
  90374. * @returns true if everything that can be done was applied
  90375. */
  90376. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90377. if (this._currentScale === -1) {
  90378. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90379. if (this._currentScale > this.maximumScale) {
  90380. this._directionOffset = -1;
  90381. }
  90382. }
  90383. this._currentScale += this._directionOffset * this.step;
  90384. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90385. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90386. };
  90387. ;
  90388. return HardwareScalingOptimization;
  90389. }(SceneOptimization));
  90390. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90391. /**
  90392. * Defines an optimization used to remove shadows
  90393. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90394. */
  90395. var ShadowsOptimization = /** @class */ (function (_super) {
  90396. __extends(ShadowsOptimization, _super);
  90397. function ShadowsOptimization() {
  90398. return _super !== null && _super.apply(this, arguments) || this;
  90399. }
  90400. /**
  90401. * Gets a string describing the action executed by the current optimization
  90402. * @return description string
  90403. */
  90404. ShadowsOptimization.prototype.getDescription = function () {
  90405. return "Turning shadows on/off";
  90406. };
  90407. /**
  90408. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90409. * @param scene defines the current scene where to apply this optimization
  90410. * @param optimizer defines the current optimizer
  90411. * @returns true if everything that can be done was applied
  90412. */
  90413. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90414. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90415. return true;
  90416. };
  90417. ;
  90418. return ShadowsOptimization;
  90419. }(SceneOptimization));
  90420. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90421. /**
  90422. * Defines an optimization used to turn post-processes off
  90423. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90424. */
  90425. var PostProcessesOptimization = /** @class */ (function (_super) {
  90426. __extends(PostProcessesOptimization, _super);
  90427. function PostProcessesOptimization() {
  90428. return _super !== null && _super.apply(this, arguments) || this;
  90429. }
  90430. /**
  90431. * Gets a string describing the action executed by the current optimization
  90432. * @return description string
  90433. */
  90434. PostProcessesOptimization.prototype.getDescription = function () {
  90435. return "Turning post-processes on/off";
  90436. };
  90437. /**
  90438. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90439. * @param scene defines the current scene where to apply this optimization
  90440. * @param optimizer defines the current optimizer
  90441. * @returns true if everything that can be done was applied
  90442. */
  90443. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90444. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90445. return true;
  90446. };
  90447. ;
  90448. return PostProcessesOptimization;
  90449. }(SceneOptimization));
  90450. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90451. /**
  90452. * Defines an optimization used to turn lens flares off
  90453. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90454. */
  90455. var LensFlaresOptimization = /** @class */ (function (_super) {
  90456. __extends(LensFlaresOptimization, _super);
  90457. function LensFlaresOptimization() {
  90458. return _super !== null && _super.apply(this, arguments) || this;
  90459. }
  90460. /**
  90461. * Gets a string describing the action executed by the current optimization
  90462. * @return description string
  90463. */
  90464. LensFlaresOptimization.prototype.getDescription = function () {
  90465. return "Turning lens flares on/off";
  90466. };
  90467. /**
  90468. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90469. * @param scene defines the current scene where to apply this optimization
  90470. * @param optimizer defines the current optimizer
  90471. * @returns true if everything that can be done was applied
  90472. */
  90473. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90474. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90475. return true;
  90476. };
  90477. ;
  90478. return LensFlaresOptimization;
  90479. }(SceneOptimization));
  90480. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90481. /**
  90482. * Defines an optimization based on user defined callback.
  90483. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90484. */
  90485. var CustomOptimization = /** @class */ (function (_super) {
  90486. __extends(CustomOptimization, _super);
  90487. function CustomOptimization() {
  90488. return _super !== null && _super.apply(this, arguments) || this;
  90489. }
  90490. /**
  90491. * Gets a string describing the action executed by the current optimization
  90492. * @returns description string
  90493. */
  90494. CustomOptimization.prototype.getDescription = function () {
  90495. if (this.onGetDescription) {
  90496. return this.onGetDescription();
  90497. }
  90498. return "Running user defined callback";
  90499. };
  90500. /**
  90501. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90502. * @param scene defines the current scene where to apply this optimization
  90503. * @param optimizer defines the current optimizer
  90504. * @returns true if everything that can be done was applied
  90505. */
  90506. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90507. if (this.onApply) {
  90508. return this.onApply(scene, optimizer);
  90509. }
  90510. return true;
  90511. };
  90512. ;
  90513. return CustomOptimization;
  90514. }(SceneOptimization));
  90515. BABYLON.CustomOptimization = CustomOptimization;
  90516. /**
  90517. * Defines an optimization used to turn particles off
  90518. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90519. */
  90520. var ParticlesOptimization = /** @class */ (function (_super) {
  90521. __extends(ParticlesOptimization, _super);
  90522. function ParticlesOptimization() {
  90523. return _super !== null && _super.apply(this, arguments) || this;
  90524. }
  90525. /**
  90526. * Gets a string describing the action executed by the current optimization
  90527. * @return description string
  90528. */
  90529. ParticlesOptimization.prototype.getDescription = function () {
  90530. return "Turning particles on/off";
  90531. };
  90532. /**
  90533. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90534. * @param scene defines the current scene where to apply this optimization
  90535. * @param optimizer defines the current optimizer
  90536. * @returns true if everything that can be done was applied
  90537. */
  90538. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90539. scene.particlesEnabled = optimizer.isInImprovementMode;
  90540. return true;
  90541. };
  90542. ;
  90543. return ParticlesOptimization;
  90544. }(SceneOptimization));
  90545. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90546. /**
  90547. * Defines an optimization used to turn render targets off
  90548. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90549. */
  90550. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90551. __extends(RenderTargetsOptimization, _super);
  90552. function RenderTargetsOptimization() {
  90553. return _super !== null && _super.apply(this, arguments) || this;
  90554. }
  90555. /**
  90556. * Gets a string describing the action executed by the current optimization
  90557. * @return description string
  90558. */
  90559. RenderTargetsOptimization.prototype.getDescription = function () {
  90560. return "Turning render targets off";
  90561. };
  90562. /**
  90563. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90564. * @param scene defines the current scene where to apply this optimization
  90565. * @param optimizer defines the current optimizer
  90566. * @returns true if everything that can be done was applied
  90567. */
  90568. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90569. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90570. return true;
  90571. };
  90572. ;
  90573. return RenderTargetsOptimization;
  90574. }(SceneOptimization));
  90575. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90576. /**
  90577. * Defines an optimization used to merge meshes with compatible materials
  90578. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90579. */
  90580. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90581. __extends(MergeMeshesOptimization, _super);
  90582. function MergeMeshesOptimization() {
  90583. var _this = _super !== null && _super.apply(this, arguments) || this;
  90584. _this._canBeMerged = function (abstractMesh) {
  90585. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90586. return false;
  90587. }
  90588. var mesh = abstractMesh;
  90589. if (!mesh.isVisible || !mesh.isEnabled()) {
  90590. return false;
  90591. }
  90592. if (mesh.instances.length > 0) {
  90593. return false;
  90594. }
  90595. if (mesh.skeleton || mesh.hasLODLevels) {
  90596. return false;
  90597. }
  90598. if (mesh.parent) {
  90599. return false;
  90600. }
  90601. return true;
  90602. };
  90603. return _this;
  90604. }
  90605. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90606. /**
  90607. * Gets or sets a boolean which defines if optimization octree has to be updated
  90608. */
  90609. get: function () {
  90610. return MergeMeshesOptimization._UpdateSelectionTree;
  90611. },
  90612. /**
  90613. * Gets or sets a boolean which defines if optimization octree has to be updated
  90614. */
  90615. set: function (value) {
  90616. MergeMeshesOptimization._UpdateSelectionTree = value;
  90617. },
  90618. enumerable: true,
  90619. configurable: true
  90620. });
  90621. /**
  90622. * Gets a string describing the action executed by the current optimization
  90623. * @return description string
  90624. */
  90625. MergeMeshesOptimization.prototype.getDescription = function () {
  90626. return "Merging similar meshes together";
  90627. };
  90628. /**
  90629. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90630. * @param scene defines the current scene where to apply this optimization
  90631. * @param optimizer defines the current optimizer
  90632. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90633. * @returns true if everything that can be done was applied
  90634. */
  90635. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90636. var globalPool = scene.meshes.slice(0);
  90637. var globalLength = globalPool.length;
  90638. for (var index = 0; index < globalLength; index++) {
  90639. var currentPool = new Array();
  90640. var current = globalPool[index];
  90641. // Checks
  90642. if (!this._canBeMerged(current)) {
  90643. continue;
  90644. }
  90645. currentPool.push(current);
  90646. // Find compatible meshes
  90647. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90648. var otherMesh = globalPool[subIndex];
  90649. if (!this._canBeMerged(otherMesh)) {
  90650. continue;
  90651. }
  90652. if (otherMesh.material !== current.material) {
  90653. continue;
  90654. }
  90655. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90656. continue;
  90657. }
  90658. currentPool.push(otherMesh);
  90659. globalLength--;
  90660. globalPool.splice(subIndex, 1);
  90661. subIndex--;
  90662. }
  90663. if (currentPool.length < 2) {
  90664. continue;
  90665. }
  90666. // Merge meshes
  90667. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90668. }
  90669. if (updateSelectionTree != undefined) {
  90670. if (updateSelectionTree) {
  90671. scene.createOrUpdateSelectionOctree();
  90672. }
  90673. }
  90674. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90675. scene.createOrUpdateSelectionOctree();
  90676. }
  90677. return true;
  90678. };
  90679. ;
  90680. MergeMeshesOptimization._UpdateSelectionTree = false;
  90681. return MergeMeshesOptimization;
  90682. }(SceneOptimization));
  90683. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90684. /**
  90685. * Defines a list of options used by SceneOptimizer
  90686. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90687. */
  90688. var SceneOptimizerOptions = /** @class */ (function () {
  90689. /**
  90690. * Creates a new list of options used by SceneOptimizer
  90691. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90692. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90693. */
  90694. function SceneOptimizerOptions(
  90695. /**
  90696. * Defines the target frame rate to reach (60 by default)
  90697. */
  90698. targetFrameRate,
  90699. /**
  90700. * Defines the interval between two checkes (2000ms by default)
  90701. */
  90702. trackerDuration) {
  90703. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90704. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90705. this.targetFrameRate = targetFrameRate;
  90706. this.trackerDuration = trackerDuration;
  90707. /**
  90708. * Gets the list of optimizations to apply
  90709. */
  90710. this.optimizations = new Array();
  90711. }
  90712. /**
  90713. * Add a new optimization
  90714. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90715. * @returns the current SceneOptimizerOptions
  90716. */
  90717. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90718. this.optimizations.push(optimization);
  90719. return this;
  90720. };
  90721. /**
  90722. * Add a new custom optimization
  90723. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90724. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90725. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90726. * @returns the current SceneOptimizerOptions
  90727. */
  90728. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90729. if (priority === void 0) { priority = 0; }
  90730. var optimization = new CustomOptimization(priority);
  90731. optimization.onApply = onApply;
  90732. optimization.onGetDescription = onGetDescription;
  90733. this.optimizations.push(optimization);
  90734. return this;
  90735. };
  90736. /**
  90737. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90738. * @param targetFrameRate defines the target frame rate (60 by default)
  90739. * @returns a SceneOptimizerOptions object
  90740. */
  90741. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90742. var result = new SceneOptimizerOptions(targetFrameRate);
  90743. var priority = 0;
  90744. result.addOptimization(new MergeMeshesOptimization(priority));
  90745. result.addOptimization(new ShadowsOptimization(priority));
  90746. result.addOptimization(new LensFlaresOptimization(priority));
  90747. // Next priority
  90748. priority++;
  90749. result.addOptimization(new PostProcessesOptimization(priority));
  90750. result.addOptimization(new ParticlesOptimization(priority));
  90751. // Next priority
  90752. priority++;
  90753. result.addOptimization(new TextureOptimization(priority, 1024));
  90754. return result;
  90755. };
  90756. /**
  90757. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90758. * @param targetFrameRate defines the target frame rate (60 by default)
  90759. * @returns a SceneOptimizerOptions object
  90760. */
  90761. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90762. var result = new SceneOptimizerOptions(targetFrameRate);
  90763. var priority = 0;
  90764. result.addOptimization(new MergeMeshesOptimization(priority));
  90765. result.addOptimization(new ShadowsOptimization(priority));
  90766. result.addOptimization(new LensFlaresOptimization(priority));
  90767. // Next priority
  90768. priority++;
  90769. result.addOptimization(new PostProcessesOptimization(priority));
  90770. result.addOptimization(new ParticlesOptimization(priority));
  90771. // Next priority
  90772. priority++;
  90773. result.addOptimization(new TextureOptimization(priority, 512));
  90774. // Next priority
  90775. priority++;
  90776. result.addOptimization(new RenderTargetsOptimization(priority));
  90777. // Next priority
  90778. priority++;
  90779. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90780. return result;
  90781. };
  90782. /**
  90783. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90784. * @param targetFrameRate defines the target frame rate (60 by default)
  90785. * @returns a SceneOptimizerOptions object
  90786. */
  90787. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90788. var result = new SceneOptimizerOptions(targetFrameRate);
  90789. var priority = 0;
  90790. result.addOptimization(new MergeMeshesOptimization(priority));
  90791. result.addOptimization(new ShadowsOptimization(priority));
  90792. result.addOptimization(new LensFlaresOptimization(priority));
  90793. // Next priority
  90794. priority++;
  90795. result.addOptimization(new PostProcessesOptimization(priority));
  90796. result.addOptimization(new ParticlesOptimization(priority));
  90797. // Next priority
  90798. priority++;
  90799. result.addOptimization(new TextureOptimization(priority, 256));
  90800. // Next priority
  90801. priority++;
  90802. result.addOptimization(new RenderTargetsOptimization(priority));
  90803. // Next priority
  90804. priority++;
  90805. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90806. return result;
  90807. };
  90808. return SceneOptimizerOptions;
  90809. }());
  90810. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90811. /**
  90812. * Class used to run optimizations in order to reach a target frame rate
  90813. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90814. */
  90815. var SceneOptimizer = /** @class */ (function () {
  90816. /**
  90817. * Creates a new SceneOptimizer
  90818. * @param scene defines the scene to work on
  90819. * @param options defines the options to use with the SceneOptimizer
  90820. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90821. * @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)
  90822. */
  90823. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90824. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90825. if (improvementMode === void 0) { improvementMode = false; }
  90826. var _this = this;
  90827. this._isRunning = false;
  90828. this._currentPriorityLevel = 0;
  90829. this._targetFrameRate = 60;
  90830. this._trackerDuration = 2000;
  90831. this._currentFrameRate = 0;
  90832. this._improvementMode = false;
  90833. /**
  90834. * Defines an observable called when the optimizer reaches the target frame rate
  90835. */
  90836. this.onSuccessObservable = new BABYLON.Observable();
  90837. /**
  90838. * Defines an observable called when the optimizer enables an optimization
  90839. */
  90840. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90841. /**
  90842. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90843. */
  90844. this.onFailureObservable = new BABYLON.Observable();
  90845. if (!options) {
  90846. this._options = new SceneOptimizerOptions();
  90847. }
  90848. else {
  90849. this._options = options;
  90850. }
  90851. if (this._options.targetFrameRate) {
  90852. this._targetFrameRate = this._options.targetFrameRate;
  90853. }
  90854. if (this._options.trackerDuration) {
  90855. this._trackerDuration = this._options.trackerDuration;
  90856. }
  90857. if (autoGeneratePriorities) {
  90858. var priority = 0;
  90859. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90860. var optim = _a[_i];
  90861. optim.priority = priority++;
  90862. }
  90863. }
  90864. this._improvementMode = improvementMode;
  90865. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90866. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90867. _this._sceneDisposeObserver = null;
  90868. _this.dispose();
  90869. });
  90870. }
  90871. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90872. /**
  90873. * Gets a boolean indicating if the optimizer is in improvement mode
  90874. */
  90875. get: function () {
  90876. return this._improvementMode;
  90877. },
  90878. enumerable: true,
  90879. configurable: true
  90880. });
  90881. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90882. /**
  90883. * Gets the current priority level (0 at start)
  90884. */
  90885. get: function () {
  90886. return this._currentPriorityLevel;
  90887. },
  90888. enumerable: true,
  90889. configurable: true
  90890. });
  90891. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90892. /**
  90893. * Gets the current frame rate checked by the SceneOptimizer
  90894. */
  90895. get: function () {
  90896. return this._currentFrameRate;
  90897. },
  90898. enumerable: true,
  90899. configurable: true
  90900. });
  90901. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90902. /**
  90903. * Gets or sets the current target frame rate (60 by default)
  90904. */
  90905. get: function () {
  90906. return this._targetFrameRate;
  90907. },
  90908. /**
  90909. * Gets or sets the current target frame rate (60 by default)
  90910. */
  90911. set: function (value) {
  90912. this._targetFrameRate = value;
  90913. },
  90914. enumerable: true,
  90915. configurable: true
  90916. });
  90917. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90918. /**
  90919. * Gets or sets the current interval between two checks (every 2000ms by default)
  90920. */
  90921. get: function () {
  90922. return this._trackerDuration;
  90923. },
  90924. /**
  90925. * Gets or sets the current interval between two checks (every 2000ms by default)
  90926. */
  90927. set: function (value) {
  90928. this._trackerDuration = value;
  90929. },
  90930. enumerable: true,
  90931. configurable: true
  90932. });
  90933. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90934. /**
  90935. * Gets the list of active optimizations
  90936. */
  90937. get: function () {
  90938. return this._options.optimizations;
  90939. },
  90940. enumerable: true,
  90941. configurable: true
  90942. });
  90943. /**
  90944. * Stops the current optimizer
  90945. */
  90946. SceneOptimizer.prototype.stop = function () {
  90947. this._isRunning = false;
  90948. };
  90949. /**
  90950. * Reset the optimizer to initial step (current priority level = 0)
  90951. */
  90952. SceneOptimizer.prototype.reset = function () {
  90953. this._currentPriorityLevel = 0;
  90954. };
  90955. /**
  90956. * Start the optimizer. By default it will try to reach a specific framerate
  90957. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90958. */
  90959. SceneOptimizer.prototype.start = function () {
  90960. var _this = this;
  90961. if (this._isRunning) {
  90962. return;
  90963. }
  90964. this._isRunning = true;
  90965. // Let's wait for the scene to be ready before running our check
  90966. this._scene.executeWhenReady(function () {
  90967. setTimeout(function () {
  90968. _this._checkCurrentState();
  90969. }, _this._trackerDuration);
  90970. });
  90971. };
  90972. SceneOptimizer.prototype._checkCurrentState = function () {
  90973. var _this = this;
  90974. if (!this._isRunning) {
  90975. return;
  90976. }
  90977. var scene = this._scene;
  90978. var options = this._options;
  90979. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90980. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90981. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90982. this._isRunning = false;
  90983. this.onSuccessObservable.notifyObservers(this);
  90984. return;
  90985. }
  90986. // Apply current level of optimizations
  90987. var allDone = true;
  90988. var noOptimizationApplied = true;
  90989. for (var index = 0; index < options.optimizations.length; index++) {
  90990. var optimization = options.optimizations[index];
  90991. if (optimization.priority === this._currentPriorityLevel) {
  90992. noOptimizationApplied = false;
  90993. allDone = allDone && optimization.apply(scene, this);
  90994. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90995. }
  90996. }
  90997. // If no optimization was applied, this is a failure :(
  90998. if (noOptimizationApplied) {
  90999. this._isRunning = false;
  91000. this.onFailureObservable.notifyObservers(this);
  91001. return;
  91002. }
  91003. // If all optimizations were done, move to next level
  91004. if (allDone) {
  91005. this._currentPriorityLevel++;
  91006. }
  91007. // Let's the system running for a specific amount of time before checking FPS
  91008. scene.executeWhenReady(function () {
  91009. setTimeout(function () {
  91010. _this._checkCurrentState();
  91011. }, _this._trackerDuration);
  91012. });
  91013. };
  91014. /**
  91015. * Release all resources
  91016. */
  91017. SceneOptimizer.prototype.dispose = function () {
  91018. this.stop();
  91019. this.onSuccessObservable.clear();
  91020. this.onFailureObservable.clear();
  91021. this.onNewOptimizationAppliedObservable.clear();
  91022. if (this._sceneDisposeObserver) {
  91023. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91024. }
  91025. };
  91026. /**
  91027. * Helper function to create a SceneOptimizer with one single line of code
  91028. * @param scene defines the scene to work on
  91029. * @param options defines the options to use with the SceneOptimizer
  91030. * @param onSuccess defines a callback to call on success
  91031. * @param onFailure defines a callback to call on failure
  91032. * @returns the new SceneOptimizer object
  91033. */
  91034. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91035. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91036. if (onSuccess) {
  91037. optimizer.onSuccessObservable.add(function () {
  91038. onSuccess();
  91039. });
  91040. }
  91041. if (onFailure) {
  91042. optimizer.onFailureObservable.add(function () {
  91043. onFailure();
  91044. });
  91045. }
  91046. optimizer.start();
  91047. return optimizer;
  91048. };
  91049. return SceneOptimizer;
  91050. }());
  91051. BABYLON.SceneOptimizer = SceneOptimizer;
  91052. })(BABYLON || (BABYLON = {}));
  91053. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91054. var BABYLON;
  91055. (function (BABYLON) {
  91056. var OutlineRenderer = /** @class */ (function () {
  91057. function OutlineRenderer(scene) {
  91058. this.zOffset = 1;
  91059. this._scene = scene;
  91060. }
  91061. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91062. var _this = this;
  91063. if (useOverlay === void 0) { useOverlay = false; }
  91064. var scene = this._scene;
  91065. var engine = this._scene.getEngine();
  91066. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91067. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91068. return;
  91069. }
  91070. var mesh = subMesh.getRenderingMesh();
  91071. var material = subMesh.getMaterial();
  91072. if (!material || !scene.activeCamera) {
  91073. return;
  91074. }
  91075. engine.enableEffect(this._effect);
  91076. // Logarithmic depth
  91077. if (material.useLogarithmicDepth) {
  91078. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91079. }
  91080. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91081. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91082. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91083. // Bones
  91084. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91085. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91086. }
  91087. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91088. // Alpha test
  91089. if (material && material.needAlphaTesting()) {
  91090. var alphaTexture = material.getAlphaTestTexture();
  91091. if (alphaTexture) {
  91092. this._effect.setTexture("diffuseSampler", alphaTexture);
  91093. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91094. }
  91095. }
  91096. engine.setZOffset(-this.zOffset);
  91097. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91098. engine.setZOffset(0);
  91099. };
  91100. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91101. var defines = [];
  91102. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91103. var mesh = subMesh.getMesh();
  91104. var material = subMesh.getMaterial();
  91105. if (material) {
  91106. // Alpha test
  91107. if (material.needAlphaTesting()) {
  91108. defines.push("#define ALPHATEST");
  91109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91110. attribs.push(BABYLON.VertexBuffer.UVKind);
  91111. defines.push("#define UV1");
  91112. }
  91113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91114. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91115. defines.push("#define UV2");
  91116. }
  91117. }
  91118. //Logarithmic depth
  91119. if (material.useLogarithmicDepth) {
  91120. defines.push("#define LOGARITHMICDEPTH");
  91121. }
  91122. }
  91123. // Bones
  91124. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91127. if (mesh.numBoneInfluencers > 4) {
  91128. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91129. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91130. }
  91131. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91132. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91133. }
  91134. else {
  91135. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91136. }
  91137. // Instances
  91138. if (useInstances) {
  91139. defines.push("#define INSTANCES");
  91140. attribs.push("world0");
  91141. attribs.push("world1");
  91142. attribs.push("world2");
  91143. attribs.push("world3");
  91144. }
  91145. // Get correct effect
  91146. var join = defines.join("\n");
  91147. if (this._cachedDefines !== join) {
  91148. this._cachedDefines = join;
  91149. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91150. }
  91151. return this._effect.isReady();
  91152. };
  91153. return OutlineRenderer;
  91154. }());
  91155. BABYLON.OutlineRenderer = OutlineRenderer;
  91156. })(BABYLON || (BABYLON = {}));
  91157. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91158. var BABYLON;
  91159. (function (BABYLON) {
  91160. var FaceAdjacencies = /** @class */ (function () {
  91161. function FaceAdjacencies() {
  91162. this.edges = new Array();
  91163. this.edgesConnectedCount = 0;
  91164. }
  91165. return FaceAdjacencies;
  91166. }());
  91167. var EdgesRenderer = /** @class */ (function () {
  91168. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91169. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91170. if (epsilon === void 0) { epsilon = 0.95; }
  91171. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91172. this.edgesWidthScalerForOrthographic = 1000.0;
  91173. this.edgesWidthScalerForPerspective = 50.0;
  91174. this._linesPositions = new Array();
  91175. this._linesNormals = new Array();
  91176. this._linesIndices = new Array();
  91177. this._buffers = {};
  91178. this._checkVerticesInsteadOfIndices = false;
  91179. this._source = source;
  91180. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91181. this._epsilon = epsilon;
  91182. this._prepareRessources();
  91183. this._generateEdgesLines();
  91184. }
  91185. EdgesRenderer.prototype._prepareRessources = function () {
  91186. if (this._lineShader) {
  91187. return;
  91188. }
  91189. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91190. attributes: ["position", "normal"],
  91191. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91192. });
  91193. this._lineShader.disableDepthWrite = true;
  91194. this._lineShader.backFaceCulling = false;
  91195. };
  91196. EdgesRenderer.prototype._rebuild = function () {
  91197. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91198. if (buffer) {
  91199. buffer._rebuild();
  91200. }
  91201. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91202. if (buffer) {
  91203. buffer._rebuild();
  91204. }
  91205. var scene = this._source.getScene();
  91206. var engine = scene.getEngine();
  91207. this._ib = engine.createIndexBuffer(this._linesIndices);
  91208. };
  91209. EdgesRenderer.prototype.dispose = function () {
  91210. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91211. if (buffer) {
  91212. buffer.dispose();
  91213. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91214. }
  91215. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91216. if (buffer) {
  91217. buffer.dispose();
  91218. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91219. }
  91220. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91221. this._lineShader.dispose();
  91222. };
  91223. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91224. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91225. return 0;
  91226. }
  91227. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91228. return 1;
  91229. }
  91230. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91231. return 2;
  91232. }
  91233. return -1;
  91234. };
  91235. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91236. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91237. return 0;
  91238. }
  91239. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91240. return 1;
  91241. }
  91242. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91243. return 2;
  91244. }
  91245. return -1;
  91246. };
  91247. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91248. var needToCreateLine;
  91249. if (edge === undefined) {
  91250. needToCreateLine = true;
  91251. }
  91252. else {
  91253. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91254. needToCreateLine = dotProduct < this._epsilon;
  91255. }
  91256. if (needToCreateLine) {
  91257. var offset = this._linesPositions.length / 3;
  91258. var normal = p0.subtract(p1);
  91259. normal.normalize();
  91260. // Positions
  91261. this._linesPositions.push(p0.x);
  91262. this._linesPositions.push(p0.y);
  91263. this._linesPositions.push(p0.z);
  91264. this._linesPositions.push(p0.x);
  91265. this._linesPositions.push(p0.y);
  91266. this._linesPositions.push(p0.z);
  91267. this._linesPositions.push(p1.x);
  91268. this._linesPositions.push(p1.y);
  91269. this._linesPositions.push(p1.z);
  91270. this._linesPositions.push(p1.x);
  91271. this._linesPositions.push(p1.y);
  91272. this._linesPositions.push(p1.z);
  91273. // Normals
  91274. this._linesNormals.push(p1.x);
  91275. this._linesNormals.push(p1.y);
  91276. this._linesNormals.push(p1.z);
  91277. this._linesNormals.push(-1);
  91278. this._linesNormals.push(p1.x);
  91279. this._linesNormals.push(p1.y);
  91280. this._linesNormals.push(p1.z);
  91281. this._linesNormals.push(1);
  91282. this._linesNormals.push(p0.x);
  91283. this._linesNormals.push(p0.y);
  91284. this._linesNormals.push(p0.z);
  91285. this._linesNormals.push(-1);
  91286. this._linesNormals.push(p0.x);
  91287. this._linesNormals.push(p0.y);
  91288. this._linesNormals.push(p0.z);
  91289. this._linesNormals.push(1);
  91290. // Indices
  91291. this._linesIndices.push(offset);
  91292. this._linesIndices.push(offset + 1);
  91293. this._linesIndices.push(offset + 2);
  91294. this._linesIndices.push(offset);
  91295. this._linesIndices.push(offset + 2);
  91296. this._linesIndices.push(offset + 3);
  91297. }
  91298. };
  91299. EdgesRenderer.prototype._generateEdgesLines = function () {
  91300. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91301. var indices = this._source.getIndices();
  91302. if (!indices || !positions) {
  91303. return;
  91304. }
  91305. // First let's find adjacencies
  91306. var adjacencies = new Array();
  91307. var faceNormals = new Array();
  91308. var index;
  91309. var faceAdjacencies;
  91310. // Prepare faces
  91311. for (index = 0; index < indices.length; index += 3) {
  91312. faceAdjacencies = new FaceAdjacencies();
  91313. var p0Index = indices[index];
  91314. var p1Index = indices[index + 1];
  91315. var p2Index = indices[index + 2];
  91316. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91317. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91318. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91319. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91320. faceNormal.normalize();
  91321. faceNormals.push(faceNormal);
  91322. adjacencies.push(faceAdjacencies);
  91323. }
  91324. // Scan
  91325. for (index = 0; index < adjacencies.length; index++) {
  91326. faceAdjacencies = adjacencies[index];
  91327. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91328. var otherFaceAdjacencies = adjacencies[otherIndex];
  91329. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91330. break;
  91331. }
  91332. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91333. continue;
  91334. }
  91335. var otherP0 = indices[otherIndex * 3];
  91336. var otherP1 = indices[otherIndex * 3 + 1];
  91337. var otherP2 = indices[otherIndex * 3 + 2];
  91338. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91339. var otherEdgeIndex = 0;
  91340. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91341. continue;
  91342. }
  91343. switch (edgeIndex) {
  91344. case 0:
  91345. if (this._checkVerticesInsteadOfIndices) {
  91346. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91347. }
  91348. else {
  91349. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91350. }
  91351. break;
  91352. case 1:
  91353. if (this._checkVerticesInsteadOfIndices) {
  91354. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91355. }
  91356. else {
  91357. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91358. }
  91359. break;
  91360. case 2:
  91361. if (this._checkVerticesInsteadOfIndices) {
  91362. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91363. }
  91364. else {
  91365. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91366. }
  91367. break;
  91368. }
  91369. if (otherEdgeIndex === -1) {
  91370. continue;
  91371. }
  91372. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91373. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91374. faceAdjacencies.edgesConnectedCount++;
  91375. otherFaceAdjacencies.edgesConnectedCount++;
  91376. if (faceAdjacencies.edgesConnectedCount === 3) {
  91377. break;
  91378. }
  91379. }
  91380. }
  91381. }
  91382. // Create lines
  91383. for (index = 0; index < adjacencies.length; index++) {
  91384. // 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
  91385. var current = adjacencies[index];
  91386. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91387. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91388. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91389. }
  91390. // Merge into a single mesh
  91391. var engine = this._source.getScene().getEngine();
  91392. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91393. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91394. this._ib = engine.createIndexBuffer(this._linesIndices);
  91395. this._indicesCount = this._linesIndices.length;
  91396. };
  91397. EdgesRenderer.prototype.render = function () {
  91398. var scene = this._source.getScene();
  91399. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91400. return;
  91401. }
  91402. var engine = scene.getEngine();
  91403. this._lineShader._preBind();
  91404. // VBOs
  91405. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91406. scene.resetCachedMaterial();
  91407. this._lineShader.setColor4("color", this._source.edgesColor);
  91408. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91409. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91410. }
  91411. else {
  91412. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91413. }
  91414. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91415. this._lineShader.bind(this._source.getWorldMatrix());
  91416. // Draw order
  91417. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91418. this._lineShader.unbind();
  91419. engine.setDepthWrite(true);
  91420. };
  91421. return EdgesRenderer;
  91422. }());
  91423. BABYLON.EdgesRenderer = EdgesRenderer;
  91424. })(BABYLON || (BABYLON = {}));
  91425. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91426. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91427. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91428. s = arguments[i];
  91429. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91430. t[p] = s[p];
  91431. }
  91432. return t;
  91433. };
  91434. var BABYLON;
  91435. (function (BABYLON) {
  91436. /**
  91437. * The effect layer Helps adding post process effect blended with the main pass.
  91438. *
  91439. * This can be for instance use to generate glow or higlight effects on the scene.
  91440. *
  91441. * The effect layer class can not be used directly and is intented to inherited from to be
  91442. * customized per effects.
  91443. */
  91444. var EffectLayer = /** @class */ (function () {
  91445. /**
  91446. * Instantiates a new effect Layer and references it in the scene.
  91447. * @param name The name of the layer
  91448. * @param scene The scene to use the layer in
  91449. */
  91450. function EffectLayer(
  91451. /** The Friendly of the effect in the scene */
  91452. name, scene) {
  91453. this._vertexBuffers = {};
  91454. this._maxSize = 0;
  91455. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91456. this._shouldRender = true;
  91457. this._postProcesses = [];
  91458. this._textures = [];
  91459. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91460. /**
  91461. * The clear color of the texture used to generate the glow map.
  91462. */
  91463. this.neutralColor = new BABYLON.Color4();
  91464. /**
  91465. * Specifies wether the highlight layer is enabled or not.
  91466. */
  91467. this.isEnabled = true;
  91468. /**
  91469. * An event triggered when the effect layer has been disposed.
  91470. */
  91471. this.onDisposeObservable = new BABYLON.Observable();
  91472. /**
  91473. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91474. */
  91475. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91476. /**
  91477. * An event triggered when the generated texture is being merged in the scene.
  91478. */
  91479. this.onBeforeComposeObservable = new BABYLON.Observable();
  91480. /**
  91481. * An event triggered when the generated texture has been merged in the scene.
  91482. */
  91483. this.onAfterComposeObservable = new BABYLON.Observable();
  91484. /**
  91485. * An event triggered when the efffect layer changes its size.
  91486. */
  91487. this.onSizeChangedObservable = new BABYLON.Observable();
  91488. this.name = name;
  91489. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91490. this._engine = scene.getEngine();
  91491. this._maxSize = this._engine.getCaps().maxTextureSize;
  91492. this._scene.effectLayers.push(this);
  91493. // Generate Buffers
  91494. this._generateIndexBuffer();
  91495. this._genrateVertexBuffer();
  91496. }
  91497. Object.defineProperty(EffectLayer.prototype, "camera", {
  91498. /**
  91499. * Gets the camera attached to the layer.
  91500. */
  91501. get: function () {
  91502. return this._effectLayerOptions.camera;
  91503. },
  91504. enumerable: true,
  91505. configurable: true
  91506. });
  91507. /**
  91508. * Initializes the effect layer with the required options.
  91509. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91510. */
  91511. EffectLayer.prototype._init = function (options) {
  91512. // Adapt options
  91513. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91514. this._setMainTextureSize();
  91515. this._createMainTexture();
  91516. this._createTextureAndPostProcesses();
  91517. this._mergeEffect = this._createMergeEffect();
  91518. };
  91519. /**
  91520. * Generates the index buffer of the full screen quad blending to the main canvas.
  91521. */
  91522. EffectLayer.prototype._generateIndexBuffer = function () {
  91523. // Indices
  91524. var indices = [];
  91525. indices.push(0);
  91526. indices.push(1);
  91527. indices.push(2);
  91528. indices.push(0);
  91529. indices.push(2);
  91530. indices.push(3);
  91531. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91532. };
  91533. /**
  91534. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91535. */
  91536. EffectLayer.prototype._genrateVertexBuffer = function () {
  91537. // VBO
  91538. var vertices = [];
  91539. vertices.push(1, 1);
  91540. vertices.push(-1, 1);
  91541. vertices.push(-1, -1);
  91542. vertices.push(1, -1);
  91543. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91544. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91545. };
  91546. /**
  91547. * Sets the main texture desired size which is the closest power of two
  91548. * of the engine canvas size.
  91549. */
  91550. EffectLayer.prototype._setMainTextureSize = function () {
  91551. if (this._effectLayerOptions.mainTextureFixedSize) {
  91552. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91553. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91554. }
  91555. else {
  91556. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91557. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91558. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91559. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91560. }
  91561. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91562. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91563. };
  91564. /**
  91565. * Creates the main texture for the effect layer.
  91566. */
  91567. EffectLayer.prototype._createMainTexture = function () {
  91568. var _this = this;
  91569. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91570. width: this._mainTextureDesiredSize.width,
  91571. height: this._mainTextureDesiredSize.height
  91572. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91573. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91574. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91575. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91576. this._mainTexture.anisotropicFilteringLevel = 1;
  91577. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91578. this._mainTexture.renderParticles = false;
  91579. this._mainTexture.renderList = null;
  91580. this._mainTexture.ignoreCameraViewport = true;
  91581. // Custom render function
  91582. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91583. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91584. var index;
  91585. var engine = _this._scene.getEngine();
  91586. if (depthOnlySubMeshes.length) {
  91587. engine.setColorWrite(false);
  91588. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91589. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91590. }
  91591. engine.setColorWrite(true);
  91592. }
  91593. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91594. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91595. }
  91596. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91597. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91598. }
  91599. for (index = 0; index < transparentSubMeshes.length; index++) {
  91600. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91601. }
  91602. };
  91603. this._mainTexture.onClearObservable.add(function (engine) {
  91604. engine.clear(_this.neutralColor, true, true, true);
  91605. });
  91606. };
  91607. /**
  91608. * Checks for the readiness of the element composing the layer.
  91609. * @param subMesh the mesh to check for
  91610. * @param useInstances specify wether or not to use instances to render the mesh
  91611. * @param emissiveTexture the associated emissive texture used to generate the glow
  91612. * @return true if ready otherwise, false
  91613. */
  91614. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91615. var material = subMesh.getMaterial();
  91616. if (!material) {
  91617. return false;
  91618. }
  91619. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91620. return false;
  91621. }
  91622. var defines = [];
  91623. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91624. var mesh = subMesh.getMesh();
  91625. var uv1 = false;
  91626. var uv2 = false;
  91627. // Alpha test
  91628. if (material && material.needAlphaTesting()) {
  91629. var alphaTexture = material.getAlphaTestTexture();
  91630. if (alphaTexture) {
  91631. defines.push("#define ALPHATEST");
  91632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91633. alphaTexture.coordinatesIndex === 1) {
  91634. defines.push("#define DIFFUSEUV2");
  91635. uv2 = true;
  91636. }
  91637. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91638. defines.push("#define DIFFUSEUV1");
  91639. uv1 = true;
  91640. }
  91641. }
  91642. }
  91643. // Emissive
  91644. if (emissiveTexture) {
  91645. defines.push("#define EMISSIVE");
  91646. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91647. emissiveTexture.coordinatesIndex === 1) {
  91648. defines.push("#define EMISSIVEUV2");
  91649. uv2 = true;
  91650. }
  91651. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91652. defines.push("#define EMISSIVEUV1");
  91653. uv1 = true;
  91654. }
  91655. }
  91656. if (uv1) {
  91657. attribs.push(BABYLON.VertexBuffer.UVKind);
  91658. defines.push("#define UV1");
  91659. }
  91660. if (uv2) {
  91661. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91662. defines.push("#define UV2");
  91663. }
  91664. // Bones
  91665. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91666. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91667. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91668. if (mesh.numBoneInfluencers > 4) {
  91669. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91670. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91671. }
  91672. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91673. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91674. }
  91675. else {
  91676. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91677. }
  91678. // Morph targets
  91679. var manager = mesh.morphTargetManager;
  91680. var morphInfluencers = 0;
  91681. if (manager) {
  91682. if (manager.numInfluencers > 0) {
  91683. defines.push("#define MORPHTARGETS");
  91684. morphInfluencers = manager.numInfluencers;
  91685. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91686. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91687. }
  91688. }
  91689. // Instances
  91690. if (useInstances) {
  91691. defines.push("#define INSTANCES");
  91692. attribs.push("world0");
  91693. attribs.push("world1");
  91694. attribs.push("world2");
  91695. attribs.push("world3");
  91696. }
  91697. // Get correct effect
  91698. var join = defines.join("\n");
  91699. if (this._cachedDefines !== join) {
  91700. this._cachedDefines = join;
  91701. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91702. }
  91703. return this._effectLayerMapGenerationEffect.isReady();
  91704. };
  91705. /**
  91706. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91707. */
  91708. EffectLayer.prototype.render = function () {
  91709. var currentEffect = this._mergeEffect;
  91710. // Check
  91711. if (!currentEffect.isReady())
  91712. return;
  91713. for (var i = 0; i < this._postProcesses.length; i++) {
  91714. if (!this._postProcesses[i].isReady()) {
  91715. return;
  91716. }
  91717. }
  91718. var engine = this._scene.getEngine();
  91719. this.onBeforeComposeObservable.notifyObservers(this);
  91720. // Render
  91721. engine.enableEffect(currentEffect);
  91722. engine.setState(false);
  91723. // VBOs
  91724. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91725. // Cache
  91726. var previousAlphaMode = engine.getAlphaMode();
  91727. // Go Blend.
  91728. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91729. // Blends the map on the main canvas.
  91730. this._internalRender(currentEffect);
  91731. // Restore Alpha
  91732. engine.setAlphaMode(previousAlphaMode);
  91733. this.onAfterComposeObservable.notifyObservers(this);
  91734. // Handle size changes.
  91735. var size = this._mainTexture.getSize();
  91736. this._setMainTextureSize();
  91737. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91738. // Recreate RTT and post processes on size change.
  91739. this.onSizeChangedObservable.notifyObservers(this);
  91740. this._disposeTextureAndPostProcesses();
  91741. this._createMainTexture();
  91742. this._createTextureAndPostProcesses();
  91743. }
  91744. };
  91745. /**
  91746. * Determine if a given mesh will be used in the current effect.
  91747. * @param mesh mesh to test
  91748. * @returns true if the mesh will be used
  91749. */
  91750. EffectLayer.prototype.hasMesh = function (mesh) {
  91751. return true;
  91752. };
  91753. /**
  91754. * Returns true if the layer contains information to display, otherwise false.
  91755. * @returns true if the glow layer should be rendered
  91756. */
  91757. EffectLayer.prototype.shouldRender = function () {
  91758. return this.isEnabled && this._shouldRender;
  91759. };
  91760. /**
  91761. * Returns true if the mesh should render, otherwise false.
  91762. * @param mesh The mesh to render
  91763. * @returns true if it should render otherwise false
  91764. */
  91765. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91766. return true;
  91767. };
  91768. /**
  91769. * Returns true if the mesh should render, otherwise false.
  91770. * @param mesh The mesh to render
  91771. * @returns true if it should render otherwise false
  91772. */
  91773. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91774. return true;
  91775. };
  91776. /**
  91777. * Renders the submesh passed in parameter to the generation map.
  91778. */
  91779. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91780. var _this = this;
  91781. if (!this.shouldRender()) {
  91782. return;
  91783. }
  91784. var material = subMesh.getMaterial();
  91785. var mesh = subMesh.getRenderingMesh();
  91786. var scene = this._scene;
  91787. var engine = scene.getEngine();
  91788. if (!material) {
  91789. return;
  91790. }
  91791. // Do not block in blend mode.
  91792. if (material.needAlphaBlendingForMesh(mesh)) {
  91793. return;
  91794. }
  91795. // Culling
  91796. engine.setState(material.backFaceCulling);
  91797. // Managing instances
  91798. var batch = mesh._getInstancesRenderList(subMesh._id);
  91799. if (batch.mustReturn) {
  91800. return;
  91801. }
  91802. // Early Exit per mesh
  91803. if (!this._shouldRenderMesh(mesh)) {
  91804. return;
  91805. }
  91806. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91807. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91808. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91809. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91810. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91811. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91812. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91813. // Alpha test
  91814. if (material && material.needAlphaTesting()) {
  91815. var alphaTexture = material.getAlphaTestTexture();
  91816. if (alphaTexture) {
  91817. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91818. var textureMatrix = alphaTexture.getTextureMatrix();
  91819. if (textureMatrix) {
  91820. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91821. }
  91822. }
  91823. }
  91824. // Glow emissive only
  91825. if (this._emissiveTextureAndColor.texture) {
  91826. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91827. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91828. }
  91829. // Bones
  91830. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91831. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91832. }
  91833. // Morph targets
  91834. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91835. // Draw
  91836. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91837. }
  91838. else {
  91839. // Need to reset refresh rate of the shadowMap
  91840. this._mainTexture.resetRefreshCounter();
  91841. }
  91842. };
  91843. /**
  91844. * Rebuild the required buffers.
  91845. * @hidden Internal use only.
  91846. */
  91847. EffectLayer.prototype._rebuild = function () {
  91848. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91849. if (vb) {
  91850. vb._rebuild();
  91851. }
  91852. this._generateIndexBuffer();
  91853. };
  91854. /**
  91855. * Dispose only the render target textures and post process.
  91856. */
  91857. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91858. this._mainTexture.dispose();
  91859. for (var i = 0; i < this._postProcesses.length; i++) {
  91860. if (this._postProcesses[i]) {
  91861. this._postProcesses[i].dispose();
  91862. }
  91863. }
  91864. this._postProcesses = [];
  91865. for (var i = 0; i < this._textures.length; i++) {
  91866. if (this._textures[i]) {
  91867. this._textures[i].dispose();
  91868. }
  91869. }
  91870. this._textures = [];
  91871. };
  91872. /**
  91873. * Dispose the highlight layer and free resources.
  91874. */
  91875. EffectLayer.prototype.dispose = function () {
  91876. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91877. if (vertexBuffer) {
  91878. vertexBuffer.dispose();
  91879. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91880. }
  91881. if (this._indexBuffer) {
  91882. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91883. this._indexBuffer = null;
  91884. }
  91885. // Clean textures and post processes
  91886. this._disposeTextureAndPostProcesses();
  91887. // Remove from scene
  91888. var index = this._scene.effectLayers.indexOf(this, 0);
  91889. if (index > -1) {
  91890. this._scene.effectLayers.splice(index, 1);
  91891. }
  91892. // Callback
  91893. this.onDisposeObservable.notifyObservers(this);
  91894. this.onDisposeObservable.clear();
  91895. this.onBeforeRenderMainTextureObservable.clear();
  91896. this.onBeforeComposeObservable.clear();
  91897. this.onAfterComposeObservable.clear();
  91898. this.onSizeChangedObservable.clear();
  91899. };
  91900. /**
  91901. * Gets the class name of the effect layer
  91902. * @returns the string with the class name of the effect layer
  91903. */
  91904. EffectLayer.prototype.getClassName = function () {
  91905. return "EffectLayer";
  91906. };
  91907. /**
  91908. * Creates an effect layer from parsed effect layer data
  91909. * @param parsedEffectLayer defines effect layer data
  91910. * @param scene defines the current scene
  91911. * @param rootUrl defines the root URL containing the effect layer information
  91912. * @returns a parsed effect Layer
  91913. */
  91914. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91915. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91916. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91917. };
  91918. __decorate([
  91919. BABYLON.serialize()
  91920. ], EffectLayer.prototype, "name", void 0);
  91921. __decorate([
  91922. BABYLON.serializeAsColor4()
  91923. ], EffectLayer.prototype, "neutralColor", void 0);
  91924. __decorate([
  91925. BABYLON.serialize()
  91926. ], EffectLayer.prototype, "isEnabled", void 0);
  91927. __decorate([
  91928. BABYLON.serializeAsCameraReference()
  91929. ], EffectLayer.prototype, "camera", null);
  91930. return EffectLayer;
  91931. }());
  91932. BABYLON.EffectLayer = EffectLayer;
  91933. })(BABYLON || (BABYLON = {}));
  91934. //# sourceMappingURL=babylon.effectLayer.js.map
  91935. var BABYLON;
  91936. (function (BABYLON) {
  91937. /**
  91938. * Special Glow Blur post process only blurring the alpha channel
  91939. * It enforces keeping the most luminous color in the color channel.
  91940. */
  91941. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91942. __extends(GlowBlurPostProcess, _super);
  91943. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91945. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91946. _this.direction = direction;
  91947. _this.kernel = kernel;
  91948. _this.onApplyObservable.add(function (effect) {
  91949. effect.setFloat2("screenSize", _this.width, _this.height);
  91950. effect.setVector2("direction", _this.direction);
  91951. effect.setFloat("blurWidth", _this.kernel);
  91952. });
  91953. return _this;
  91954. }
  91955. return GlowBlurPostProcess;
  91956. }(BABYLON.PostProcess));
  91957. /**
  91958. * The highlight layer Helps adding a glow effect around a mesh.
  91959. *
  91960. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91961. * glowy meshes to your scene.
  91962. *
  91963. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91964. */
  91965. var HighlightLayer = /** @class */ (function (_super) {
  91966. __extends(HighlightLayer, _super);
  91967. /**
  91968. * Instantiates a new highlight Layer and references it to the scene..
  91969. * @param name The name of the layer
  91970. * @param scene The scene to use the layer in
  91971. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91972. */
  91973. function HighlightLayer(name, scene, options) {
  91974. var _this = _super.call(this, name, scene) || this;
  91975. _this.name = name;
  91976. /**
  91977. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91978. */
  91979. _this.innerGlow = true;
  91980. /**
  91981. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91982. */
  91983. _this.outerGlow = true;
  91984. /**
  91985. * An event triggered when the highlight layer is being blurred.
  91986. */
  91987. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91988. /**
  91989. * An event triggered when the highlight layer has been blurred.
  91990. */
  91991. _this.onAfterBlurObservable = new BABYLON.Observable();
  91992. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91993. _this._meshes = {};
  91994. _this._excludedMeshes = {};
  91995. _this.neutralColor = HighlightLayer.NeutralColor;
  91996. // Warn on stencil
  91997. if (!_this._engine.isStencilEnable) {
  91998. 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 }");
  91999. }
  92000. // Adapt options
  92001. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92002. // Initialize the layer
  92003. _this._init({
  92004. alphaBlendingMode: _this._options.alphaBlendingMode,
  92005. camera: _this._options.camera,
  92006. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92007. mainTextureRatio: _this._options.mainTextureRatio
  92008. });
  92009. // Do not render as long as no meshes have been added
  92010. _this._shouldRender = false;
  92011. return _this;
  92012. }
  92013. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92014. /**
  92015. * Gets the horizontal size of the blur.
  92016. */
  92017. get: function () {
  92018. return this._horizontalBlurPostprocess.kernel;
  92019. },
  92020. /**
  92021. * Specifies the horizontal size of the blur.
  92022. */
  92023. set: function (value) {
  92024. this._horizontalBlurPostprocess.kernel = value;
  92025. },
  92026. enumerable: true,
  92027. configurable: true
  92028. });
  92029. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92030. /**
  92031. * Gets the vertical size of the blur.
  92032. */
  92033. get: function () {
  92034. return this._verticalBlurPostprocess.kernel;
  92035. },
  92036. /**
  92037. * Specifies the vertical size of the blur.
  92038. */
  92039. set: function (value) {
  92040. this._verticalBlurPostprocess.kernel = value;
  92041. },
  92042. enumerable: true,
  92043. configurable: true
  92044. });
  92045. /**
  92046. * Get the effect name of the layer.
  92047. * @return The effect name
  92048. */
  92049. HighlightLayer.prototype.getEffectName = function () {
  92050. return HighlightLayer.EffectName;
  92051. };
  92052. /**
  92053. * Create the merge effect. This is the shader use to blit the information back
  92054. * to the main canvas at the end of the scene rendering.
  92055. */
  92056. HighlightLayer.prototype._createMergeEffect = function () {
  92057. // Effect
  92058. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92059. };
  92060. /**
  92061. * Creates the render target textures and post processes used in the highlight layer.
  92062. */
  92063. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92064. var _this = this;
  92065. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92066. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92067. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92068. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92069. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92070. width: blurTextureWidth,
  92071. height: blurTextureHeight
  92072. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92073. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92074. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92075. this._blurTexture.anisotropicFilteringLevel = 16;
  92076. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92077. this._blurTexture.renderParticles = false;
  92078. this._blurTexture.ignoreCameraViewport = true;
  92079. this._textures = [this._blurTexture];
  92080. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92081. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92082. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92083. effect.setTexture("textureSampler", _this._mainTexture);
  92084. });
  92085. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92086. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92087. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92088. });
  92089. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92090. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92091. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92092. });
  92093. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92094. }
  92095. else {
  92096. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92097. width: blurTextureWidth,
  92098. height: blurTextureHeight
  92099. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92100. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92101. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92102. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92103. effect.setTexture("textureSampler", _this._mainTexture);
  92104. });
  92105. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92106. width: blurTextureWidth,
  92107. height: blurTextureHeight
  92108. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92109. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92110. }
  92111. this._mainTexture.onAfterUnbindObservable.add(function () {
  92112. _this.onBeforeBlurObservable.notifyObservers(_this);
  92113. var internalTexture = _this._blurTexture.getInternalTexture();
  92114. if (internalTexture) {
  92115. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92116. }
  92117. _this.onAfterBlurObservable.notifyObservers(_this);
  92118. });
  92119. // Prevent autoClear.
  92120. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92121. };
  92122. /**
  92123. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92124. */
  92125. HighlightLayer.prototype.needStencil = function () {
  92126. return true;
  92127. };
  92128. /**
  92129. * Checks for the readiness of the element composing the layer.
  92130. * @param subMesh the mesh to check for
  92131. * @param useInstances specify wether or not to use instances to render the mesh
  92132. * @param emissiveTexture the associated emissive texture used to generate the glow
  92133. * @return true if ready otherwise, false
  92134. */
  92135. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92136. var material = subMesh.getMaterial();
  92137. var mesh = subMesh.getRenderingMesh();
  92138. if (!material || !mesh || !this._meshes) {
  92139. return false;
  92140. }
  92141. var emissiveTexture = null;
  92142. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92143. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92144. emissiveTexture = material.emissiveTexture;
  92145. }
  92146. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92147. };
  92148. /**
  92149. * Implementation specific of rendering the generating effect on the main canvas.
  92150. * @param effect The effect used to render through
  92151. */
  92152. HighlightLayer.prototype._internalRender = function (effect) {
  92153. // Texture
  92154. effect.setTexture("textureSampler", this._blurTexture);
  92155. // Cache
  92156. var engine = this._engine;
  92157. var previousStencilBuffer = engine.getStencilBuffer();
  92158. var previousStencilFunction = engine.getStencilFunction();
  92159. var previousStencilMask = engine.getStencilMask();
  92160. var previousStencilOperationPass = engine.getStencilOperationPass();
  92161. var previousStencilOperationFail = engine.getStencilOperationFail();
  92162. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92163. var previousStencilReference = engine.getStencilFunctionReference();
  92164. // Stencil operations
  92165. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92166. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92167. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92168. // Draw order
  92169. engine.setStencilMask(0x00);
  92170. engine.setStencilBuffer(true);
  92171. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92172. // 2 passes inner outer
  92173. if (this.outerGlow) {
  92174. effect.setFloat("offset", 0);
  92175. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92176. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92177. }
  92178. if (this.innerGlow) {
  92179. effect.setFloat("offset", 1);
  92180. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92181. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92182. }
  92183. // Restore Cache
  92184. engine.setStencilFunction(previousStencilFunction);
  92185. engine.setStencilMask(previousStencilMask);
  92186. engine.setStencilBuffer(previousStencilBuffer);
  92187. engine.setStencilOperationPass(previousStencilOperationPass);
  92188. engine.setStencilOperationFail(previousStencilOperationFail);
  92189. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92190. engine.setStencilFunctionReference(previousStencilReference);
  92191. };
  92192. /**
  92193. * Returns true if the layer contains information to display, otherwise false.
  92194. */
  92195. HighlightLayer.prototype.shouldRender = function () {
  92196. if (_super.prototype.shouldRender.call(this)) {
  92197. return this._meshes ? true : false;
  92198. }
  92199. return false;
  92200. };
  92201. /**
  92202. * Returns true if the mesh should render, otherwise false.
  92203. * @param mesh The mesh to render
  92204. * @returns true if it should render otherwise false
  92205. */
  92206. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92207. // Excluded Mesh
  92208. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92209. return false;
  92210. }
  92211. ;
  92212. return true;
  92213. };
  92214. /**
  92215. * Sets the required values for both the emissive texture and and the main color.
  92216. */
  92217. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92218. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92219. if (highlightLayerMesh) {
  92220. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92221. }
  92222. else {
  92223. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92224. }
  92225. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92226. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92227. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92228. }
  92229. else {
  92230. this._emissiveTextureAndColor.texture = null;
  92231. }
  92232. };
  92233. /**
  92234. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92235. * @param mesh The mesh to exclude from the highlight layer
  92236. */
  92237. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92238. if (!this._excludedMeshes) {
  92239. return;
  92240. }
  92241. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92242. if (!meshExcluded) {
  92243. this._excludedMeshes[mesh.uniqueId] = {
  92244. mesh: mesh,
  92245. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92246. mesh.getEngine().setStencilBuffer(false);
  92247. }),
  92248. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92249. mesh.getEngine().setStencilBuffer(true);
  92250. }),
  92251. };
  92252. }
  92253. };
  92254. /**
  92255. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92256. * @param mesh The mesh to highlight
  92257. */
  92258. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92259. if (!this._excludedMeshes) {
  92260. return;
  92261. }
  92262. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92263. if (meshExcluded) {
  92264. if (meshExcluded.beforeRender) {
  92265. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92266. }
  92267. if (meshExcluded.afterRender) {
  92268. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92269. }
  92270. }
  92271. this._excludedMeshes[mesh.uniqueId] = null;
  92272. };
  92273. /**
  92274. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92275. * @param mesh mesh to test
  92276. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92277. */
  92278. HighlightLayer.prototype.hasMesh = function (mesh) {
  92279. if (!this._meshes) {
  92280. return false;
  92281. }
  92282. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92283. };
  92284. /**
  92285. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92286. * @param mesh The mesh to highlight
  92287. * @param color The color of the highlight
  92288. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92289. */
  92290. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92291. var _this = this;
  92292. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92293. if (!this._meshes) {
  92294. return;
  92295. }
  92296. var meshHighlight = this._meshes[mesh.uniqueId];
  92297. if (meshHighlight) {
  92298. meshHighlight.color = color;
  92299. }
  92300. else {
  92301. this._meshes[mesh.uniqueId] = {
  92302. mesh: mesh,
  92303. color: color,
  92304. // Lambda required for capture due to Observable this context
  92305. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92306. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92307. _this._defaultStencilReference(mesh);
  92308. }
  92309. else {
  92310. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92311. }
  92312. }),
  92313. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92314. glowEmissiveOnly: glowEmissiveOnly
  92315. };
  92316. }
  92317. this._shouldRender = true;
  92318. };
  92319. /**
  92320. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92321. * @param mesh The mesh to highlight
  92322. */
  92323. HighlightLayer.prototype.removeMesh = function (mesh) {
  92324. if (!this._meshes) {
  92325. return;
  92326. }
  92327. var meshHighlight = this._meshes[mesh.uniqueId];
  92328. if (meshHighlight) {
  92329. if (meshHighlight.observerHighlight) {
  92330. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92331. }
  92332. if (meshHighlight.observerDefault) {
  92333. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92334. }
  92335. delete this._meshes[mesh.uniqueId];
  92336. }
  92337. this._shouldRender = false;
  92338. for (var meshHighlightToCheck in this._meshes) {
  92339. if (this._meshes[meshHighlightToCheck]) {
  92340. this._shouldRender = true;
  92341. break;
  92342. }
  92343. }
  92344. };
  92345. /**
  92346. * Force the stencil to the normal expected value for none glowing parts
  92347. */
  92348. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92349. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92350. };
  92351. /**
  92352. * Free any resources and references associated to a mesh.
  92353. * Internal use
  92354. * @param mesh The mesh to free.
  92355. */
  92356. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92357. this.removeMesh(mesh);
  92358. this.removeExcludedMesh(mesh);
  92359. };
  92360. /**
  92361. * Dispose the highlight layer and free resources.
  92362. */
  92363. HighlightLayer.prototype.dispose = function () {
  92364. if (this._meshes) {
  92365. // Clean mesh references
  92366. for (var id in this._meshes) {
  92367. var meshHighlight = this._meshes[id];
  92368. if (meshHighlight && meshHighlight.mesh) {
  92369. if (meshHighlight.observerHighlight) {
  92370. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92371. }
  92372. if (meshHighlight.observerDefault) {
  92373. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92374. }
  92375. }
  92376. }
  92377. this._meshes = null;
  92378. }
  92379. if (this._excludedMeshes) {
  92380. for (var id in this._excludedMeshes) {
  92381. var meshHighlight = this._excludedMeshes[id];
  92382. if (meshHighlight) {
  92383. if (meshHighlight.beforeRender) {
  92384. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92385. }
  92386. if (meshHighlight.afterRender) {
  92387. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92388. }
  92389. }
  92390. }
  92391. this._excludedMeshes = null;
  92392. }
  92393. _super.prototype.dispose.call(this);
  92394. };
  92395. /**
  92396. * Gets the class name of the effect layer
  92397. * @returns the string with the class name of the effect layer
  92398. */
  92399. HighlightLayer.prototype.getClassName = function () {
  92400. return "HighlightLayer";
  92401. };
  92402. /**
  92403. * Serializes this Highlight layer
  92404. * @returns a serialized Highlight layer object
  92405. */
  92406. HighlightLayer.prototype.serialize = function () {
  92407. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92408. serializationObject.customType = "BABYLON.HighlightLayer";
  92409. // Highlighted meshes
  92410. serializationObject.meshes = [];
  92411. if (this._meshes) {
  92412. for (var m in this._meshes) {
  92413. var mesh = this._meshes[m];
  92414. if (mesh) {
  92415. serializationObject.meshes.push({
  92416. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92417. color: mesh.color.asArray(),
  92418. meshId: mesh.mesh.id
  92419. });
  92420. }
  92421. }
  92422. }
  92423. // Excluded meshes
  92424. serializationObject.excludedMeshes = [];
  92425. if (this._excludedMeshes) {
  92426. for (var e in this._excludedMeshes) {
  92427. var excludedMesh = this._excludedMeshes[e];
  92428. if (excludedMesh) {
  92429. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92430. }
  92431. }
  92432. }
  92433. return serializationObject;
  92434. };
  92435. /**
  92436. * Creates a Highlight layer from parsed Highlight layer data
  92437. * @param parsedHightlightLayer defines the Highlight layer data
  92438. * @param scene defines the current scene
  92439. * @param rootUrl defines the root URL containing the Highlight layer information
  92440. * @returns a parsed Highlight layer
  92441. */
  92442. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92443. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92444. var index;
  92445. // Excluded meshes
  92446. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92447. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92448. if (mesh) {
  92449. hl.addExcludedMesh(mesh);
  92450. }
  92451. }
  92452. // Included meshes
  92453. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92454. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92455. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92456. if (mesh) {
  92457. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92458. }
  92459. }
  92460. return hl;
  92461. };
  92462. /**
  92463. * Effect Name of the highlight layer.
  92464. */
  92465. HighlightLayer.EffectName = "HighlightLayer";
  92466. /**
  92467. * The neutral color used during the preparation of the glow effect.
  92468. * This is black by default as the blend operation is a blend operation.
  92469. */
  92470. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92471. /**
  92472. * Stencil value used for glowing meshes.
  92473. */
  92474. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92475. /**
  92476. * Stencil value used for the other meshes in the scene.
  92477. */
  92478. HighlightLayer.NormalMeshStencilReference = 0x01;
  92479. __decorate([
  92480. BABYLON.serialize()
  92481. ], HighlightLayer.prototype, "innerGlow", void 0);
  92482. __decorate([
  92483. BABYLON.serialize()
  92484. ], HighlightLayer.prototype, "outerGlow", void 0);
  92485. __decorate([
  92486. BABYLON.serialize()
  92487. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92488. __decorate([
  92489. BABYLON.serialize()
  92490. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92491. __decorate([
  92492. BABYLON.serialize("options")
  92493. ], HighlightLayer.prototype, "_options", void 0);
  92494. return HighlightLayer;
  92495. }(BABYLON.EffectLayer));
  92496. BABYLON.HighlightLayer = HighlightLayer;
  92497. })(BABYLON || (BABYLON = {}));
  92498. //# sourceMappingURL=babylon.highlightLayer.js.map
  92499. var BABYLON;
  92500. (function (BABYLON) {
  92501. /**
  92502. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92503. *
  92504. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92505. * glowy meshes to your scene.
  92506. *
  92507. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92508. */
  92509. var GlowLayer = /** @class */ (function (_super) {
  92510. __extends(GlowLayer, _super);
  92511. /**
  92512. * Instantiates a new glow Layer and references it to the scene.
  92513. * @param name The name of the layer
  92514. * @param scene The scene to use the layer in
  92515. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92516. */
  92517. function GlowLayer(name, scene, options) {
  92518. var _this = _super.call(this, name, scene) || this;
  92519. _this._intensity = 1.0;
  92520. _this._includedOnlyMeshes = [];
  92521. _this._excludedMeshes = [];
  92522. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92523. // Adapt options
  92524. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92525. // Initialize the layer
  92526. _this._init({
  92527. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92528. camera: _this._options.camera,
  92529. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92530. mainTextureRatio: _this._options.mainTextureRatio
  92531. });
  92532. return _this;
  92533. }
  92534. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92535. /**
  92536. * Gets the kernel size of the blur.
  92537. */
  92538. get: function () {
  92539. return this._horizontalBlurPostprocess1.kernel;
  92540. },
  92541. /**
  92542. * Sets the kernel size of the blur.
  92543. */
  92544. set: function (value) {
  92545. this._horizontalBlurPostprocess1.kernel = value;
  92546. this._verticalBlurPostprocess1.kernel = value;
  92547. this._horizontalBlurPostprocess2.kernel = value;
  92548. this._verticalBlurPostprocess2.kernel = value;
  92549. },
  92550. enumerable: true,
  92551. configurable: true
  92552. });
  92553. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92554. /**
  92555. * Gets the glow intensity.
  92556. */
  92557. get: function () {
  92558. return this._intensity;
  92559. },
  92560. /**
  92561. * Sets the glow intensity.
  92562. */
  92563. set: function (value) {
  92564. this._intensity = value;
  92565. },
  92566. enumerable: true,
  92567. configurable: true
  92568. });
  92569. /**
  92570. * Get the effect name of the layer.
  92571. * @return The effect name
  92572. */
  92573. GlowLayer.prototype.getEffectName = function () {
  92574. return GlowLayer.EffectName;
  92575. };
  92576. /**
  92577. * Create the merge effect. This is the shader use to blit the information back
  92578. * to the main canvas at the end of the scene rendering.
  92579. */
  92580. GlowLayer.prototype._createMergeEffect = function () {
  92581. // Effect
  92582. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92583. };
  92584. /**
  92585. * Creates the render target textures and post processes used in the glow layer.
  92586. */
  92587. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92588. var _this = this;
  92589. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92590. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92591. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92592. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92593. var textureType = 0;
  92594. if (this._engine.getCaps().textureHalfFloatRender) {
  92595. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92596. }
  92597. else {
  92598. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92599. }
  92600. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92601. width: blurTextureWidth,
  92602. height: blurTextureHeight
  92603. }, this._scene, false, true, textureType);
  92604. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92605. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92606. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92607. this._blurTexture1.renderParticles = false;
  92608. this._blurTexture1.ignoreCameraViewport = true;
  92609. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92610. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92611. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92612. width: blurTextureWidth2,
  92613. height: blurTextureHeight2
  92614. }, this._scene, false, true, textureType);
  92615. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92616. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92617. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92618. this._blurTexture2.renderParticles = false;
  92619. this._blurTexture2.ignoreCameraViewport = true;
  92620. this._textures = [this._blurTexture1, this._blurTexture2];
  92621. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92622. width: blurTextureWidth,
  92623. height: blurTextureHeight
  92624. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92625. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92626. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92627. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92628. effect.setTexture("textureSampler", _this._mainTexture);
  92629. });
  92630. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92631. width: blurTextureWidth,
  92632. height: blurTextureHeight
  92633. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92634. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92635. width: blurTextureWidth2,
  92636. height: blurTextureHeight2
  92637. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92638. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92639. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92640. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92641. effect.setTexture("textureSampler", _this._blurTexture1);
  92642. });
  92643. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92644. width: blurTextureWidth2,
  92645. height: blurTextureHeight2
  92646. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92647. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92648. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92649. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92650. this._mainTexture.samples = this._options.mainTextureSamples;
  92651. this._mainTexture.onAfterUnbindObservable.add(function () {
  92652. var internalTexture = _this._blurTexture1.getInternalTexture();
  92653. if (internalTexture) {
  92654. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92655. internalTexture = _this._blurTexture2.getInternalTexture();
  92656. if (internalTexture) {
  92657. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92658. }
  92659. }
  92660. });
  92661. // Prevent autoClear.
  92662. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92663. };
  92664. /**
  92665. * Checks for the readiness of the element composing the layer.
  92666. * @param subMesh the mesh to check for
  92667. * @param useInstances specify wether or not to use instances to render the mesh
  92668. * @param emissiveTexture the associated emissive texture used to generate the glow
  92669. * @return true if ready otherwise, false
  92670. */
  92671. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92672. var material = subMesh.getMaterial();
  92673. var mesh = subMesh.getRenderingMesh();
  92674. if (!material || !mesh) {
  92675. return false;
  92676. }
  92677. var emissiveTexture = material.emissiveTexture;
  92678. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92679. };
  92680. /**
  92681. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92682. */
  92683. GlowLayer.prototype.needStencil = function () {
  92684. return false;
  92685. };
  92686. /**
  92687. * Implementation specific of rendering the generating effect on the main canvas.
  92688. * @param effect The effect used to render through
  92689. */
  92690. GlowLayer.prototype._internalRender = function (effect) {
  92691. // Texture
  92692. effect.setTexture("textureSampler", this._blurTexture1);
  92693. effect.setTexture("textureSampler2", this._blurTexture2);
  92694. effect.setFloat("offset", this._intensity);
  92695. // Cache
  92696. var engine = this._engine;
  92697. var previousStencilBuffer = engine.getStencilBuffer();
  92698. // Draw order
  92699. engine.setStencilBuffer(false);
  92700. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92701. // Draw order
  92702. engine.setStencilBuffer(previousStencilBuffer);
  92703. };
  92704. /**
  92705. * Sets the required values for both the emissive texture and and the main color.
  92706. */
  92707. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92708. var textureLevel = 1.0;
  92709. if (this.customEmissiveTextureSelector) {
  92710. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92711. }
  92712. else {
  92713. if (material) {
  92714. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92715. if (this._emissiveTextureAndColor.texture) {
  92716. textureLevel = this._emissiveTextureAndColor.texture.level;
  92717. }
  92718. }
  92719. else {
  92720. this._emissiveTextureAndColor.texture = null;
  92721. }
  92722. }
  92723. if (this.customEmissiveColorSelector) {
  92724. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92725. }
  92726. else {
  92727. if (material.emissiveColor) {
  92728. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92729. }
  92730. else {
  92731. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92732. }
  92733. }
  92734. };
  92735. /**
  92736. * Returns true if the mesh should render, otherwise false.
  92737. * @param mesh The mesh to render
  92738. * @returns true if it should render otherwise false
  92739. */
  92740. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92741. return this.hasMesh(mesh);
  92742. };
  92743. /**
  92744. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92745. * @param mesh The mesh to exclude from the glow layer
  92746. */
  92747. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92748. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92749. this._excludedMeshes.push(mesh.uniqueId);
  92750. }
  92751. };
  92752. /**
  92753. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92754. * @param mesh The mesh to remove
  92755. */
  92756. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92757. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92758. if (index !== -1) {
  92759. this._excludedMeshes.splice(index, 1);
  92760. }
  92761. };
  92762. /**
  92763. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92764. * @param mesh The mesh to include in the glow layer
  92765. */
  92766. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92767. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92768. this._includedOnlyMeshes.push(mesh.uniqueId);
  92769. }
  92770. };
  92771. /**
  92772. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92773. * @param mesh The mesh to remove
  92774. */
  92775. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92776. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92777. if (index !== -1) {
  92778. this._includedOnlyMeshes.splice(index, 1);
  92779. }
  92780. };
  92781. /**
  92782. * Determine if a given mesh will be used in the glow layer
  92783. * @param mesh The mesh to test
  92784. * @returns true if the mesh will be highlighted by the current glow layer
  92785. */
  92786. GlowLayer.prototype.hasMesh = function (mesh) {
  92787. // Included Mesh
  92788. if (this._includedOnlyMeshes.length) {
  92789. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92790. }
  92791. ;
  92792. // Excluded Mesh
  92793. if (this._excludedMeshes.length) {
  92794. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92795. }
  92796. ;
  92797. return true;
  92798. };
  92799. /**
  92800. * Free any resources and references associated to a mesh.
  92801. * Internal use
  92802. * @param mesh The mesh to free.
  92803. */
  92804. GlowLayer.prototype._disposeMesh = function (mesh) {
  92805. this.removeIncludedOnlyMesh(mesh);
  92806. this.removeExcludedMesh(mesh);
  92807. };
  92808. /**
  92809. * Gets the class name of the effect layer
  92810. * @returns the string with the class name of the effect layer
  92811. */
  92812. GlowLayer.prototype.getClassName = function () {
  92813. return "GlowLayer";
  92814. };
  92815. /**
  92816. * Serializes this glow layer
  92817. * @returns a serialized glow layer object
  92818. */
  92819. GlowLayer.prototype.serialize = function () {
  92820. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92821. serializationObject.customType = "BABYLON.GlowLayer";
  92822. var index;
  92823. // Included meshes
  92824. serializationObject.includedMeshes = [];
  92825. if (this._includedOnlyMeshes.length) {
  92826. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92827. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92828. if (mesh) {
  92829. serializationObject.includedMeshes.push(mesh.id);
  92830. }
  92831. }
  92832. }
  92833. // Excluded meshes
  92834. serializationObject.excludedMeshes = [];
  92835. if (this._excludedMeshes.length) {
  92836. for (index = 0; index < this._excludedMeshes.length; index++) {
  92837. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92838. if (mesh) {
  92839. serializationObject.excludedMeshes.push(mesh.id);
  92840. }
  92841. }
  92842. }
  92843. return serializationObject;
  92844. };
  92845. /**
  92846. * Creates a Glow Layer from parsed glow layer data
  92847. * @param parsedGlowLayer defines glow layer data
  92848. * @param scene defines the current scene
  92849. * @param rootUrl defines the root URL containing the glow layer information
  92850. * @returns a parsed Glow Layer
  92851. */
  92852. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92853. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92854. var index;
  92855. // Excluded meshes
  92856. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92857. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92858. if (mesh) {
  92859. gl.addExcludedMesh(mesh);
  92860. }
  92861. }
  92862. // Included meshes
  92863. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92864. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92865. if (mesh) {
  92866. gl.addIncludedOnlyMesh(mesh);
  92867. }
  92868. }
  92869. return gl;
  92870. };
  92871. /**
  92872. * Effect Name of the layer.
  92873. */
  92874. GlowLayer.EffectName = "GlowLayer";
  92875. /**
  92876. * The default blur kernel size used for the glow.
  92877. */
  92878. GlowLayer.DefaultBlurKernelSize = 32;
  92879. /**
  92880. * The default texture size ratio used for the glow.
  92881. */
  92882. GlowLayer.DefaultTextureRatio = 0.5;
  92883. __decorate([
  92884. BABYLON.serialize()
  92885. ], GlowLayer.prototype, "blurKernelSize", null);
  92886. __decorate([
  92887. BABYLON.serialize()
  92888. ], GlowLayer.prototype, "intensity", null);
  92889. __decorate([
  92890. BABYLON.serialize("options")
  92891. ], GlowLayer.prototype, "_options", void 0);
  92892. return GlowLayer;
  92893. }(BABYLON.EffectLayer));
  92894. BABYLON.GlowLayer = GlowLayer;
  92895. })(BABYLON || (BABYLON = {}));
  92896. //# sourceMappingURL=babylon.glowLayer.js.map
  92897. var BABYLON;
  92898. (function (BABYLON) {
  92899. /**
  92900. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92901. */
  92902. var AssetTaskState;
  92903. (function (AssetTaskState) {
  92904. /**
  92905. * Initialization
  92906. */
  92907. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92908. /**
  92909. * Running
  92910. */
  92911. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92912. /**
  92913. * Done
  92914. */
  92915. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92916. /**
  92917. * Error
  92918. */
  92919. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92920. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92921. /**
  92922. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92923. */
  92924. var AbstractAssetTask = /** @class */ (function () {
  92925. /**
  92926. * Creates a new {BABYLON.AssetsManager}
  92927. * @param name defines the name of the task
  92928. */
  92929. function AbstractAssetTask(
  92930. /**
  92931. * Task name
  92932. */ name) {
  92933. this.name = name;
  92934. this._isCompleted = false;
  92935. this._taskState = AssetTaskState.INIT;
  92936. }
  92937. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92938. /**
  92939. * Get if the task is completed
  92940. */
  92941. get: function () {
  92942. return this._isCompleted;
  92943. },
  92944. enumerable: true,
  92945. configurable: true
  92946. });
  92947. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92948. /**
  92949. * Gets the current state of the task
  92950. */
  92951. get: function () {
  92952. return this._taskState;
  92953. },
  92954. enumerable: true,
  92955. configurable: true
  92956. });
  92957. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92958. /**
  92959. * Gets the current error object (if task is in error)
  92960. */
  92961. get: function () {
  92962. return this._errorObject;
  92963. },
  92964. enumerable: true,
  92965. configurable: true
  92966. });
  92967. /**
  92968. * Internal only
  92969. * @hidden
  92970. */
  92971. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92972. if (this._errorObject) {
  92973. return;
  92974. }
  92975. this._errorObject = {
  92976. message: message,
  92977. exception: exception
  92978. };
  92979. };
  92980. /**
  92981. * Execute the current task
  92982. * @param scene defines the scene where you want your assets to be loaded
  92983. * @param onSuccess is a callback called when the task is successfully executed
  92984. * @param onError is a callback called if an error occurs
  92985. */
  92986. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92987. var _this = this;
  92988. this._taskState = AssetTaskState.RUNNING;
  92989. this.runTask(scene, function () {
  92990. _this.onDoneCallback(onSuccess, onError);
  92991. }, function (msg, exception) {
  92992. _this.onErrorCallback(onError, msg, exception);
  92993. });
  92994. };
  92995. /**
  92996. * Execute the current task
  92997. * @param scene defines the scene where you want your assets to be loaded
  92998. * @param onSuccess is a callback called when the task is successfully executed
  92999. * @param onError is a callback called if an error occurs
  93000. */
  93001. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93002. throw new Error("runTask is not implemented");
  93003. };
  93004. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93005. this._taskState = AssetTaskState.ERROR;
  93006. this._errorObject = {
  93007. message: message,
  93008. exception: exception
  93009. };
  93010. if (this.onError) {
  93011. this.onError(this, message, exception);
  93012. }
  93013. onError();
  93014. };
  93015. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93016. try {
  93017. this._taskState = AssetTaskState.DONE;
  93018. this._isCompleted = true;
  93019. if (this.onSuccess) {
  93020. this.onSuccess(this);
  93021. }
  93022. onSuccess();
  93023. }
  93024. catch (e) {
  93025. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93026. }
  93027. };
  93028. return AbstractAssetTask;
  93029. }());
  93030. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93031. /**
  93032. * Class used to share progress information about assets loading
  93033. */
  93034. var AssetsProgressEvent = /** @class */ (function () {
  93035. /**
  93036. * Creates a {BABYLON.AssetsProgressEvent}
  93037. * @param remainingCount defines the number of remaining tasks to process
  93038. * @param totalCount defines the total number of tasks
  93039. * @param task defines the task that was just processed
  93040. */
  93041. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93042. this.remainingCount = remainingCount;
  93043. this.totalCount = totalCount;
  93044. this.task = task;
  93045. }
  93046. return AssetsProgressEvent;
  93047. }());
  93048. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93049. /**
  93050. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93051. */
  93052. var MeshAssetTask = /** @class */ (function (_super) {
  93053. __extends(MeshAssetTask, _super);
  93054. /**
  93055. * Creates a new {BABYLON.MeshAssetTask}
  93056. * @param name defines the name of the task
  93057. * @param meshesNames defines the list of mesh's names you want to load
  93058. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93059. * @param sceneFilename defines the filename of the scene to load from
  93060. */
  93061. function MeshAssetTask(
  93062. /**
  93063. * Defines the name of the task
  93064. */
  93065. name,
  93066. /**
  93067. * Defines the list of mesh's names you want to load
  93068. */
  93069. meshesNames,
  93070. /**
  93071. * Defines the root url to use as a base to load your meshes and associated resources
  93072. */
  93073. rootUrl,
  93074. /**
  93075. * Defines the filename of the scene to load from
  93076. */
  93077. sceneFilename) {
  93078. var _this = _super.call(this, name) || this;
  93079. _this.name = name;
  93080. _this.meshesNames = meshesNames;
  93081. _this.rootUrl = rootUrl;
  93082. _this.sceneFilename = sceneFilename;
  93083. return _this;
  93084. }
  93085. /**
  93086. * Execute the current task
  93087. * @param scene defines the scene where you want your assets to be loaded
  93088. * @param onSuccess is a callback called when the task is successfully executed
  93089. * @param onError is a callback called if an error occurs
  93090. */
  93091. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93092. var _this = this;
  93093. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93094. _this.loadedMeshes = meshes;
  93095. _this.loadedParticleSystems = particleSystems;
  93096. _this.loadedSkeletons = skeletons;
  93097. onSuccess();
  93098. }, null, function (scene, message, exception) {
  93099. onError(message, exception);
  93100. });
  93101. };
  93102. return MeshAssetTask;
  93103. }(AbstractAssetTask));
  93104. BABYLON.MeshAssetTask = MeshAssetTask;
  93105. /**
  93106. * Define a task used by {BABYLON.AssetsManager} to load text content
  93107. */
  93108. var TextFileAssetTask = /** @class */ (function (_super) {
  93109. __extends(TextFileAssetTask, _super);
  93110. /**
  93111. * Creates a new TextFileAssetTask object
  93112. * @param name defines the name of the task
  93113. * @param url defines the location of the file to load
  93114. */
  93115. function TextFileAssetTask(
  93116. /**
  93117. * Defines the name of the task
  93118. */
  93119. name,
  93120. /**
  93121. * Defines the location of the file to load
  93122. */
  93123. url) {
  93124. var _this = _super.call(this, name) || this;
  93125. _this.name = name;
  93126. _this.url = url;
  93127. return _this;
  93128. }
  93129. /**
  93130. * Execute the current task
  93131. * @param scene defines the scene where you want your assets to be loaded
  93132. * @param onSuccess is a callback called when the task is successfully executed
  93133. * @param onError is a callback called if an error occurs
  93134. */
  93135. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93136. var _this = this;
  93137. scene._loadFile(this.url, function (data) {
  93138. _this.text = data;
  93139. onSuccess();
  93140. }, undefined, false, false, function (request, exception) {
  93141. if (request) {
  93142. onError(request.status + " " + request.statusText, exception);
  93143. }
  93144. });
  93145. };
  93146. return TextFileAssetTask;
  93147. }(AbstractAssetTask));
  93148. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93149. /**
  93150. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93151. */
  93152. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93153. __extends(BinaryFileAssetTask, _super);
  93154. /**
  93155. * Creates a new BinaryFileAssetTask object
  93156. * @param name defines the name of the new task
  93157. * @param url defines the location of the file to load
  93158. */
  93159. function BinaryFileAssetTask(
  93160. /**
  93161. * Defines the name of the task
  93162. */
  93163. name,
  93164. /**
  93165. * Defines the location of the file to load
  93166. */
  93167. url) {
  93168. var _this = _super.call(this, name) || this;
  93169. _this.name = name;
  93170. _this.url = url;
  93171. return _this;
  93172. }
  93173. /**
  93174. * Execute the current task
  93175. * @param scene defines the scene where you want your assets to be loaded
  93176. * @param onSuccess is a callback called when the task is successfully executed
  93177. * @param onError is a callback called if an error occurs
  93178. */
  93179. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93180. var _this = this;
  93181. scene._loadFile(this.url, function (data) {
  93182. _this.data = data;
  93183. onSuccess();
  93184. }, undefined, true, true, function (request, exception) {
  93185. if (request) {
  93186. onError(request.status + " " + request.statusText, exception);
  93187. }
  93188. });
  93189. };
  93190. return BinaryFileAssetTask;
  93191. }(AbstractAssetTask));
  93192. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93193. /**
  93194. * Define a task used by {BABYLON.AssetsManager} to load images
  93195. */
  93196. var ImageAssetTask = /** @class */ (function (_super) {
  93197. __extends(ImageAssetTask, _super);
  93198. /**
  93199. * Creates a new ImageAssetTask
  93200. * @param name defines the name of the task
  93201. * @param url defines the location of the image to load
  93202. */
  93203. function ImageAssetTask(
  93204. /**
  93205. * Defines the name of the task
  93206. */
  93207. name,
  93208. /**
  93209. * Defines the location of the image to load
  93210. */
  93211. url) {
  93212. var _this = _super.call(this, name) || this;
  93213. _this.name = name;
  93214. _this.url = url;
  93215. return _this;
  93216. }
  93217. /**
  93218. * Execute the current task
  93219. * @param scene defines the scene where you want your assets to be loaded
  93220. * @param onSuccess is a callback called when the task is successfully executed
  93221. * @param onError is a callback called if an error occurs
  93222. */
  93223. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93224. var _this = this;
  93225. var img = new Image();
  93226. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93227. img.onload = function () {
  93228. _this.image = img;
  93229. onSuccess();
  93230. };
  93231. img.onerror = function (err) {
  93232. onError("Error loading image", err);
  93233. };
  93234. img.src = this.url;
  93235. };
  93236. return ImageAssetTask;
  93237. }(AbstractAssetTask));
  93238. BABYLON.ImageAssetTask = ImageAssetTask;
  93239. /**
  93240. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93241. */
  93242. var TextureAssetTask = /** @class */ (function (_super) {
  93243. __extends(TextureAssetTask, _super);
  93244. /**
  93245. * Creates a new TextureAssetTask object
  93246. * @param name defines the name of the task
  93247. * @param url defines the location of the file to load
  93248. * @param noMipmap defines if mipmap should not be generated (default is false)
  93249. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93250. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93251. */
  93252. function TextureAssetTask(
  93253. /**
  93254. * Defines the name of the task
  93255. */
  93256. name,
  93257. /**
  93258. * Defines the location of the file to load
  93259. */
  93260. url,
  93261. /**
  93262. * Defines if mipmap should not be generated (default is false)
  93263. */
  93264. noMipmap,
  93265. /**
  93266. * Defines if texture must be inverted on Y axis (default is false)
  93267. */
  93268. invertY,
  93269. /**
  93270. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93271. */
  93272. samplingMode) {
  93273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93274. var _this = _super.call(this, name) || this;
  93275. _this.name = name;
  93276. _this.url = url;
  93277. _this.noMipmap = noMipmap;
  93278. _this.invertY = invertY;
  93279. _this.samplingMode = samplingMode;
  93280. return _this;
  93281. }
  93282. /**
  93283. * Execute the current task
  93284. * @param scene defines the scene where you want your assets to be loaded
  93285. * @param onSuccess is a callback called when the task is successfully executed
  93286. * @param onError is a callback called if an error occurs
  93287. */
  93288. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93289. var onload = function () {
  93290. onSuccess();
  93291. };
  93292. var onerror = function (message, exception) {
  93293. onError(message, exception);
  93294. };
  93295. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93296. };
  93297. return TextureAssetTask;
  93298. }(AbstractAssetTask));
  93299. BABYLON.TextureAssetTask = TextureAssetTask;
  93300. /**
  93301. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93302. */
  93303. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93304. __extends(CubeTextureAssetTask, _super);
  93305. /**
  93306. * Creates a new CubeTextureAssetTask
  93307. * @param name defines the name of the task
  93308. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93309. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93310. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93311. * @param files defines the explicit list of files (undefined by default)
  93312. */
  93313. function CubeTextureAssetTask(
  93314. /**
  93315. * Defines the name of the task
  93316. */
  93317. name,
  93318. /**
  93319. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93320. */
  93321. url,
  93322. /**
  93323. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93324. */
  93325. extensions,
  93326. /**
  93327. * Defines if mipmaps should not be generated (default is false)
  93328. */
  93329. noMipmap,
  93330. /**
  93331. * Defines the explicit list of files (undefined by default)
  93332. */
  93333. files) {
  93334. var _this = _super.call(this, name) || this;
  93335. _this.name = name;
  93336. _this.url = url;
  93337. _this.extensions = extensions;
  93338. _this.noMipmap = noMipmap;
  93339. _this.files = files;
  93340. return _this;
  93341. }
  93342. /**
  93343. * Execute the current task
  93344. * @param scene defines the scene where you want your assets to be loaded
  93345. * @param onSuccess is a callback called when the task is successfully executed
  93346. * @param onError is a callback called if an error occurs
  93347. */
  93348. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93349. var onload = function () {
  93350. onSuccess();
  93351. };
  93352. var onerror = function (message, exception) {
  93353. onError(message, exception);
  93354. };
  93355. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93356. };
  93357. return CubeTextureAssetTask;
  93358. }(AbstractAssetTask));
  93359. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93360. /**
  93361. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93362. */
  93363. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93364. __extends(HDRCubeTextureAssetTask, _super);
  93365. /**
  93366. * Creates a new HDRCubeTextureAssetTask object
  93367. * @param name defines the name of the task
  93368. * @param url defines the location of the file to load
  93369. * @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.
  93370. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93371. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93372. * @param gammaSpace 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)
  93373. * @param reserved Internal use only
  93374. */
  93375. function HDRCubeTextureAssetTask(
  93376. /**
  93377. * Defines the name of the task
  93378. */
  93379. name,
  93380. /**
  93381. * Defines the location of the file to load
  93382. */
  93383. url,
  93384. /**
  93385. * Defines the desired size (the more it increases the longer the generation will be)
  93386. */
  93387. size,
  93388. /**
  93389. * Defines if mipmaps should not be generated (default is false)
  93390. */
  93391. noMipmap,
  93392. /**
  93393. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93394. */
  93395. generateHarmonics,
  93396. /**
  93397. * 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)
  93398. */
  93399. gammaSpace,
  93400. /**
  93401. * Internal Use Only
  93402. */
  93403. reserved) {
  93404. if (noMipmap === void 0) { noMipmap = false; }
  93405. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93406. if (gammaSpace === void 0) { gammaSpace = false; }
  93407. if (reserved === void 0) { reserved = false; }
  93408. var _this = _super.call(this, name) || this;
  93409. _this.name = name;
  93410. _this.url = url;
  93411. _this.size = size;
  93412. _this.noMipmap = noMipmap;
  93413. _this.generateHarmonics = generateHarmonics;
  93414. _this.gammaSpace = gammaSpace;
  93415. _this.reserved = reserved;
  93416. return _this;
  93417. }
  93418. /**
  93419. * Execute the current task
  93420. * @param scene defines the scene where you want your assets to be loaded
  93421. * @param onSuccess is a callback called when the task is successfully executed
  93422. * @param onError is a callback called if an error occurs
  93423. */
  93424. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93425. var onload = function () {
  93426. onSuccess();
  93427. };
  93428. var onerror = function (message, exception) {
  93429. onError(message, exception);
  93430. };
  93431. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93432. };
  93433. return HDRCubeTextureAssetTask;
  93434. }(AbstractAssetTask));
  93435. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93436. /**
  93437. * This class can be used to easily import assets into a scene
  93438. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93439. */
  93440. var AssetsManager = /** @class */ (function () {
  93441. /**
  93442. * Creates a new AssetsManager
  93443. * @param scene defines the scene to work on
  93444. */
  93445. function AssetsManager(scene) {
  93446. this._isLoading = false;
  93447. this._tasks = new Array();
  93448. this._waitingTasksCount = 0;
  93449. this._totalTasksCount = 0;
  93450. /**
  93451. * Observable called when all tasks are processed
  93452. */
  93453. this.onTaskSuccessObservable = new BABYLON.Observable();
  93454. /**
  93455. * Observable called when a task had an error
  93456. */
  93457. this.onTaskErrorObservable = new BABYLON.Observable();
  93458. /**
  93459. * Observable called when a task is successful
  93460. */
  93461. this.onTasksDoneObservable = new BABYLON.Observable();
  93462. /**
  93463. * Observable called when a task is done (whatever the result is)
  93464. */
  93465. this.onProgressObservable = new BABYLON.Observable();
  93466. /**
  93467. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93468. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93469. */
  93470. this.useDefaultLoadingScreen = true;
  93471. this._scene = scene;
  93472. }
  93473. /**
  93474. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93475. * @param taskName defines the name of the new task
  93476. * @param meshesNames defines the name of meshes to load
  93477. * @param rootUrl defines the root url to use to locate files
  93478. * @param sceneFilename defines the filename of the scene file
  93479. * @returns a new {BABYLON.MeshAssetTask} object
  93480. */
  93481. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93482. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93483. this._tasks.push(task);
  93484. return task;
  93485. };
  93486. /**
  93487. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93488. * @param taskName defines the name of the new task
  93489. * @param url defines the url of the file to load
  93490. * @returns a new {BABYLON.TextFileAssetTask} object
  93491. */
  93492. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93493. var task = new TextFileAssetTask(taskName, url);
  93494. this._tasks.push(task);
  93495. return task;
  93496. };
  93497. /**
  93498. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93499. * @param taskName defines the name of the new task
  93500. * @param url defines the url of the file to load
  93501. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93502. */
  93503. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93504. var task = new BinaryFileAssetTask(taskName, url);
  93505. this._tasks.push(task);
  93506. return task;
  93507. };
  93508. /**
  93509. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93510. * @param taskName defines the name of the new task
  93511. * @param url defines the url of the file to load
  93512. * @returns a new {BABYLON.ImageAssetTask} object
  93513. */
  93514. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93515. var task = new ImageAssetTask(taskName, url);
  93516. this._tasks.push(task);
  93517. return task;
  93518. };
  93519. /**
  93520. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93521. * @param taskName defines the name of the new task
  93522. * @param url defines the url of the file to load
  93523. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93524. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93525. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93526. * @returns a new {BABYLON.TextureAssetTask} object
  93527. */
  93528. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93530. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93531. this._tasks.push(task);
  93532. return task;
  93533. };
  93534. /**
  93535. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93536. * @param taskName defines the name of the new task
  93537. * @param url defines the url of the file to load
  93538. * @param extensions defines the extension to use to load the cube map (can be null)
  93539. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93540. * @param files defines the list of files to load (can be null)
  93541. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93542. */
  93543. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93544. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93545. this._tasks.push(task);
  93546. return task;
  93547. };
  93548. /**
  93549. *
  93550. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93551. * @param taskName defines the name of the new task
  93552. * @param url defines the url of the file to load
  93553. * @param size defines the size you want for the cubemap (can be null)
  93554. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93555. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93556. * @param gammaSpace 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)
  93557. * @param reserved Internal use only
  93558. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93559. */
  93560. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93561. if (noMipmap === void 0) { noMipmap = false; }
  93562. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93563. if (gammaSpace === void 0) { gammaSpace = false; }
  93564. if (reserved === void 0) { reserved = false; }
  93565. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93566. this._tasks.push(task);
  93567. return task;
  93568. };
  93569. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93570. var _this = this;
  93571. this._waitingTasksCount--;
  93572. try {
  93573. if (task.taskState === AssetTaskState.DONE) {
  93574. // Let's remove successfull tasks
  93575. BABYLON.Tools.SetImmediate(function () {
  93576. var index = _this._tasks.indexOf(task);
  93577. if (index > -1) {
  93578. _this._tasks.splice(index, 1);
  93579. }
  93580. });
  93581. }
  93582. if (this.onProgress) {
  93583. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93584. }
  93585. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93586. }
  93587. catch (e) {
  93588. BABYLON.Tools.Error("Error running progress callbacks.");
  93589. console.log(e);
  93590. }
  93591. if (this._waitingTasksCount === 0) {
  93592. try {
  93593. if (this.onFinish) {
  93594. this.onFinish(this._tasks);
  93595. }
  93596. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93597. }
  93598. catch (e) {
  93599. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93600. console.log(e);
  93601. }
  93602. this._isLoading = false;
  93603. this._scene.getEngine().hideLoadingUI();
  93604. }
  93605. };
  93606. AssetsManager.prototype._runTask = function (task) {
  93607. var _this = this;
  93608. var done = function () {
  93609. try {
  93610. if (_this.onTaskSuccess) {
  93611. _this.onTaskSuccess(task);
  93612. }
  93613. _this.onTaskSuccessObservable.notifyObservers(task);
  93614. _this._decreaseWaitingTasksCount(task);
  93615. }
  93616. catch (e) {
  93617. error("Error executing task success callbacks", e);
  93618. }
  93619. };
  93620. var error = function (message, exception) {
  93621. task._setErrorObject(message, exception);
  93622. if (_this.onTaskError) {
  93623. _this.onTaskError(task);
  93624. }
  93625. _this.onTaskErrorObservable.notifyObservers(task);
  93626. _this._decreaseWaitingTasksCount(task);
  93627. };
  93628. task.run(this._scene, done, error);
  93629. };
  93630. /**
  93631. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93632. * @return the current instance of the {BABYLON.AssetsManager}
  93633. */
  93634. AssetsManager.prototype.reset = function () {
  93635. this._isLoading = false;
  93636. this._tasks = new Array();
  93637. return this;
  93638. };
  93639. /**
  93640. * Start the loading process
  93641. * @return the current instance of the {BABYLON.AssetsManager}
  93642. */
  93643. AssetsManager.prototype.load = function () {
  93644. if (this._isLoading) {
  93645. return this;
  93646. }
  93647. this._isLoading = true;
  93648. this._waitingTasksCount = this._tasks.length;
  93649. this._totalTasksCount = this._tasks.length;
  93650. if (this._waitingTasksCount === 0) {
  93651. this._isLoading = false;
  93652. if (this.onFinish) {
  93653. this.onFinish(this._tasks);
  93654. }
  93655. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93656. return this;
  93657. }
  93658. if (this.useDefaultLoadingScreen) {
  93659. this._scene.getEngine().displayLoadingUI();
  93660. }
  93661. for (var index = 0; index < this._tasks.length; index++) {
  93662. var task = this._tasks[index];
  93663. this._runTask(task);
  93664. }
  93665. return this;
  93666. };
  93667. return AssetsManager;
  93668. }());
  93669. BABYLON.AssetsManager = AssetsManager;
  93670. })(BABYLON || (BABYLON = {}));
  93671. //# sourceMappingURL=babylon.assetsManager.js.map
  93672. var BABYLON;
  93673. (function (BABYLON) {
  93674. var serializedGeometries = [];
  93675. var serializeGeometry = function (geometry, serializationGeometries) {
  93676. if (serializedGeometries[geometry.id]) {
  93677. return;
  93678. }
  93679. if (geometry.doNotSerialize) {
  93680. return;
  93681. }
  93682. if (geometry instanceof BABYLON.BoxGeometry) {
  93683. serializationGeometries.boxes.push(geometry.serialize());
  93684. }
  93685. else if (geometry instanceof BABYLON.SphereGeometry) {
  93686. serializationGeometries.spheres.push(geometry.serialize());
  93687. }
  93688. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93689. serializationGeometries.cylinders.push(geometry.serialize());
  93690. }
  93691. else if (geometry instanceof BABYLON.TorusGeometry) {
  93692. serializationGeometries.toruses.push(geometry.serialize());
  93693. }
  93694. else if (geometry instanceof BABYLON.GroundGeometry) {
  93695. serializationGeometries.grounds.push(geometry.serialize());
  93696. }
  93697. else if (geometry instanceof BABYLON.Plane) {
  93698. serializationGeometries.planes.push(geometry.serialize());
  93699. }
  93700. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93701. serializationGeometries.torusKnots.push(geometry.serialize());
  93702. }
  93703. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93704. throw new Error("Unknown primitive type");
  93705. }
  93706. else {
  93707. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93708. }
  93709. serializedGeometries[geometry.id] = true;
  93710. };
  93711. var serializeMesh = function (mesh, serializationScene) {
  93712. var serializationObject = {};
  93713. // Geometry
  93714. var geometry = mesh._geometry;
  93715. if (geometry) {
  93716. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93717. // 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
  93718. serializeGeometry(geometry, serializationScene.geometries);
  93719. }
  93720. }
  93721. // Custom
  93722. if (mesh.serialize) {
  93723. mesh.serialize(serializationObject);
  93724. }
  93725. return serializationObject;
  93726. };
  93727. var finalizeSingleMesh = function (mesh, serializationObject) {
  93728. //only works if the mesh is already loaded
  93729. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93730. //serialize material
  93731. if (mesh.material) {
  93732. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93733. serializationObject.materials = serializationObject.materials || [];
  93734. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93735. serializationObject.materials.push(mesh.material.serialize());
  93736. }
  93737. }
  93738. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93739. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93740. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93741. serializationObject.multiMaterials.push(mesh.material.serialize());
  93742. }
  93743. }
  93744. }
  93745. //serialize geometry
  93746. var geometry = mesh._geometry;
  93747. if (geometry) {
  93748. if (!serializationObject.geometries) {
  93749. serializationObject.geometries = {};
  93750. serializationObject.geometries.boxes = [];
  93751. serializationObject.geometries.spheres = [];
  93752. serializationObject.geometries.cylinders = [];
  93753. serializationObject.geometries.toruses = [];
  93754. serializationObject.geometries.grounds = [];
  93755. serializationObject.geometries.planes = [];
  93756. serializationObject.geometries.torusKnots = [];
  93757. serializationObject.geometries.vertexData = [];
  93758. }
  93759. serializeGeometry(geometry, serializationObject.geometries);
  93760. }
  93761. // Skeletons
  93762. if (mesh.skeleton) {
  93763. serializationObject.skeletons = serializationObject.skeletons || [];
  93764. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93765. }
  93766. //serialize the actual mesh
  93767. serializationObject.meshes = serializationObject.meshes || [];
  93768. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93769. }
  93770. };
  93771. var SceneSerializer = /** @class */ (function () {
  93772. function SceneSerializer() {
  93773. }
  93774. SceneSerializer.ClearCache = function () {
  93775. serializedGeometries = [];
  93776. };
  93777. SceneSerializer.Serialize = function (scene) {
  93778. var serializationObject = {};
  93779. SceneSerializer.ClearCache();
  93780. // Scene
  93781. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93782. serializationObject.autoClear = scene.autoClear;
  93783. serializationObject.clearColor = scene.clearColor.asArray();
  93784. serializationObject.ambientColor = scene.ambientColor.asArray();
  93785. serializationObject.gravity = scene.gravity.asArray();
  93786. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93787. serializationObject.workerCollisions = scene.workerCollisions;
  93788. // Fog
  93789. if (scene.fogMode && scene.fogMode !== 0) {
  93790. serializationObject.fogMode = scene.fogMode;
  93791. serializationObject.fogColor = scene.fogColor.asArray();
  93792. serializationObject.fogStart = scene.fogStart;
  93793. serializationObject.fogEnd = scene.fogEnd;
  93794. serializationObject.fogDensity = scene.fogDensity;
  93795. }
  93796. //Physics
  93797. if (scene.isPhysicsEnabled()) {
  93798. var physicEngine = scene.getPhysicsEngine();
  93799. if (physicEngine) {
  93800. serializationObject.physicsEnabled = true;
  93801. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93802. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93803. }
  93804. }
  93805. // Metadata
  93806. if (scene.metadata) {
  93807. serializationObject.metadata = scene.metadata;
  93808. }
  93809. // Morph targets
  93810. serializationObject.morphTargetManagers = [];
  93811. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93812. var abstractMesh = _a[_i];
  93813. var manager = abstractMesh.morphTargetManager;
  93814. if (manager) {
  93815. serializationObject.morphTargetManagers.push(manager.serialize());
  93816. }
  93817. }
  93818. // Lights
  93819. serializationObject.lights = [];
  93820. var index;
  93821. var light;
  93822. for (index = 0; index < scene.lights.length; index++) {
  93823. light = scene.lights[index];
  93824. if (!light.doNotSerialize) {
  93825. serializationObject.lights.push(light.serialize());
  93826. }
  93827. }
  93828. // Cameras
  93829. serializationObject.cameras = [];
  93830. for (index = 0; index < scene.cameras.length; index++) {
  93831. var camera = scene.cameras[index];
  93832. if (!camera.doNotSerialize) {
  93833. serializationObject.cameras.push(camera.serialize());
  93834. }
  93835. }
  93836. if (scene.activeCamera) {
  93837. serializationObject.activeCameraID = scene.activeCamera.id;
  93838. }
  93839. // Animations
  93840. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93841. // Materials
  93842. serializationObject.materials = [];
  93843. serializationObject.multiMaterials = [];
  93844. var material;
  93845. for (index = 0; index < scene.materials.length; index++) {
  93846. material = scene.materials[index];
  93847. if (!material.doNotSerialize) {
  93848. serializationObject.materials.push(material.serialize());
  93849. }
  93850. }
  93851. // MultiMaterials
  93852. serializationObject.multiMaterials = [];
  93853. for (index = 0; index < scene.multiMaterials.length; index++) {
  93854. var multiMaterial = scene.multiMaterials[index];
  93855. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93856. }
  93857. // Environment texture
  93858. if (scene.environmentTexture) {
  93859. serializationObject.environmentTexture = scene.environmentTexture.name;
  93860. }
  93861. // Skeletons
  93862. serializationObject.skeletons = [];
  93863. for (index = 0; index < scene.skeletons.length; index++) {
  93864. var skeleton = scene.skeletons[index];
  93865. if (!skeleton.doNotSerialize) {
  93866. serializationObject.skeletons.push(skeleton.serialize());
  93867. }
  93868. }
  93869. // Transform nodes
  93870. serializationObject.transformNodes = [];
  93871. for (index = 0; index < scene.transformNodes.length; index++) {
  93872. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93873. }
  93874. // Geometries
  93875. serializationObject.geometries = {};
  93876. serializationObject.geometries.boxes = [];
  93877. serializationObject.geometries.spheres = [];
  93878. serializationObject.geometries.cylinders = [];
  93879. serializationObject.geometries.toruses = [];
  93880. serializationObject.geometries.grounds = [];
  93881. serializationObject.geometries.planes = [];
  93882. serializationObject.geometries.torusKnots = [];
  93883. serializationObject.geometries.vertexData = [];
  93884. serializedGeometries = [];
  93885. var geometries = scene.getGeometries();
  93886. for (index = 0; index < geometries.length; index++) {
  93887. var geometry = geometries[index];
  93888. if (geometry.isReady()) {
  93889. serializeGeometry(geometry, serializationObject.geometries);
  93890. }
  93891. }
  93892. // Meshes
  93893. serializationObject.meshes = [];
  93894. for (index = 0; index < scene.meshes.length; index++) {
  93895. var abstractMesh = scene.meshes[index];
  93896. if (abstractMesh instanceof BABYLON.Mesh) {
  93897. var mesh = abstractMesh;
  93898. if (!mesh.doNotSerialize) {
  93899. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93900. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93901. }
  93902. }
  93903. }
  93904. }
  93905. // Particles Systems
  93906. serializationObject.particleSystems = [];
  93907. for (index = 0; index < scene.particleSystems.length; index++) {
  93908. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93909. }
  93910. // Lens flares
  93911. serializationObject.lensFlareSystems = [];
  93912. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93913. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93914. }
  93915. // Shadows
  93916. serializationObject.shadowGenerators = [];
  93917. for (index = 0; index < scene.lights.length; index++) {
  93918. light = scene.lights[index];
  93919. var shadowGenerator = light.getShadowGenerator();
  93920. if (shadowGenerator) {
  93921. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93922. }
  93923. }
  93924. // Action Manager
  93925. if (scene.actionManager) {
  93926. serializationObject.actions = scene.actionManager.serialize("scene");
  93927. }
  93928. // Audio
  93929. serializationObject.sounds = [];
  93930. for (index = 0; index < scene.soundTracks.length; index++) {
  93931. var soundtrack = scene.soundTracks[index];
  93932. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93933. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93934. }
  93935. }
  93936. // Effect layers
  93937. serializationObject.effectLayers = [];
  93938. for (index = 0; index < scene.effectLayers.length; index++) {
  93939. var layer = scene.effectLayers[index];
  93940. if (layer.serialize) {
  93941. serializationObject.effectLayers.push(layer.serialize());
  93942. }
  93943. }
  93944. return serializationObject;
  93945. };
  93946. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93947. if (withParents === void 0) { withParents = false; }
  93948. if (withChildren === void 0) { withChildren = false; }
  93949. var serializationObject = {};
  93950. SceneSerializer.ClearCache();
  93951. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93952. if (withParents || withChildren) {
  93953. //deliberate for loop! not for each, appended should be processed as well.
  93954. for (var i = 0; i < toSerialize.length; ++i) {
  93955. if (withChildren) {
  93956. toSerialize[i].getDescendants().forEach(function (node) {
  93957. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93958. toSerialize.push(node);
  93959. }
  93960. });
  93961. }
  93962. //make sure the array doesn't contain the object already
  93963. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93964. toSerialize.push(toSerialize[i].parent);
  93965. }
  93966. }
  93967. }
  93968. toSerialize.forEach(function (mesh) {
  93969. finalizeSingleMesh(mesh, serializationObject);
  93970. });
  93971. return serializationObject;
  93972. };
  93973. return SceneSerializer;
  93974. }());
  93975. BABYLON.SceneSerializer = SceneSerializer;
  93976. })(BABYLON || (BABYLON = {}));
  93977. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93978. var BABYLON;
  93979. (function (BABYLON) {
  93980. var ReflectionProbe = /** @class */ (function () {
  93981. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93982. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93983. var _this = this;
  93984. this.name = name;
  93985. this._viewMatrix = BABYLON.Matrix.Identity();
  93986. this._target = BABYLON.Vector3.Zero();
  93987. this._add = BABYLON.Vector3.Zero();
  93988. this._invertYAxis = false;
  93989. this.position = BABYLON.Vector3.Zero();
  93990. this._scene = scene;
  93991. this._scene.reflectionProbes.push(this);
  93992. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93993. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93994. switch (faceIndex) {
  93995. case 0:
  93996. _this._add.copyFromFloats(1, 0, 0);
  93997. break;
  93998. case 1:
  93999. _this._add.copyFromFloats(-1, 0, 0);
  94000. break;
  94001. case 2:
  94002. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94003. break;
  94004. case 3:
  94005. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94006. break;
  94007. case 4:
  94008. _this._add.copyFromFloats(0, 0, 1);
  94009. break;
  94010. case 5:
  94011. _this._add.copyFromFloats(0, 0, -1);
  94012. break;
  94013. }
  94014. if (_this._attachedMesh) {
  94015. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94016. }
  94017. _this.position.addToRef(_this._add, _this._target);
  94018. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94019. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94020. scene._forcedViewPosition = _this.position;
  94021. });
  94022. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94023. scene._forcedViewPosition = null;
  94024. scene.updateTransformMatrix(true);
  94025. });
  94026. if (scene.activeCamera) {
  94027. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94028. }
  94029. }
  94030. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94031. get: function () {
  94032. return this._renderTargetTexture.samples;
  94033. },
  94034. set: function (value) {
  94035. this._renderTargetTexture.samples = value;
  94036. },
  94037. enumerable: true,
  94038. configurable: true
  94039. });
  94040. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94041. get: function () {
  94042. return this._renderTargetTexture.refreshRate;
  94043. },
  94044. set: function (value) {
  94045. this._renderTargetTexture.refreshRate = value;
  94046. },
  94047. enumerable: true,
  94048. configurable: true
  94049. });
  94050. ReflectionProbe.prototype.getScene = function () {
  94051. return this._scene;
  94052. };
  94053. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94054. get: function () {
  94055. return this._renderTargetTexture;
  94056. },
  94057. enumerable: true,
  94058. configurable: true
  94059. });
  94060. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94061. get: function () {
  94062. return this._renderTargetTexture.renderList;
  94063. },
  94064. enumerable: true,
  94065. configurable: true
  94066. });
  94067. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94068. this._attachedMesh = mesh;
  94069. };
  94070. /**
  94071. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94072. *
  94073. * @param renderingGroupId The rendering group id corresponding to its index
  94074. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94075. */
  94076. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94077. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94078. };
  94079. ReflectionProbe.prototype.dispose = function () {
  94080. var index = this._scene.reflectionProbes.indexOf(this);
  94081. if (index !== -1) {
  94082. // Remove from the scene if found
  94083. this._scene.reflectionProbes.splice(index, 1);
  94084. }
  94085. if (this._renderTargetTexture) {
  94086. this._renderTargetTexture.dispose();
  94087. this._renderTargetTexture = null;
  94088. }
  94089. };
  94090. return ReflectionProbe;
  94091. }());
  94092. BABYLON.ReflectionProbe = ReflectionProbe;
  94093. })(BABYLON || (BABYLON = {}));
  94094. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94095. var BABYLON;
  94096. (function (BABYLON) {
  94097. var Layer = /** @class */ (function () {
  94098. function Layer(name, imgUrl, scene, isBackground, color) {
  94099. this.name = name;
  94100. this.scale = new BABYLON.Vector2(1, 1);
  94101. this.offset = new BABYLON.Vector2(0, 0);
  94102. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94103. this.layerMask = 0x0FFFFFFF;
  94104. this._vertexBuffers = {};
  94105. // Events
  94106. /**
  94107. * An event triggered when the layer is disposed.
  94108. */
  94109. this.onDisposeObservable = new BABYLON.Observable();
  94110. /**
  94111. * An event triggered before rendering the scene
  94112. */
  94113. this.onBeforeRenderObservable = new BABYLON.Observable();
  94114. /**
  94115. * An event triggered after rendering the scene
  94116. */
  94117. this.onAfterRenderObservable = new BABYLON.Observable();
  94118. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94119. this.isBackground = isBackground === undefined ? true : isBackground;
  94120. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94121. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94122. this._scene.layers.push(this);
  94123. var engine = this._scene.getEngine();
  94124. // VBO
  94125. var vertices = [];
  94126. vertices.push(1, 1);
  94127. vertices.push(-1, 1);
  94128. vertices.push(-1, -1);
  94129. vertices.push(1, -1);
  94130. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94131. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94132. this._createIndexBuffer();
  94133. // Effects
  94134. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94135. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94136. }
  94137. Object.defineProperty(Layer.prototype, "onDispose", {
  94138. set: function (callback) {
  94139. if (this._onDisposeObserver) {
  94140. this.onDisposeObservable.remove(this._onDisposeObserver);
  94141. }
  94142. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94143. },
  94144. enumerable: true,
  94145. configurable: true
  94146. });
  94147. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94148. set: function (callback) {
  94149. if (this._onBeforeRenderObserver) {
  94150. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94151. }
  94152. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94153. },
  94154. enumerable: true,
  94155. configurable: true
  94156. });
  94157. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94158. set: function (callback) {
  94159. if (this._onAfterRenderObserver) {
  94160. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94161. }
  94162. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94163. },
  94164. enumerable: true,
  94165. configurable: true
  94166. });
  94167. Layer.prototype._createIndexBuffer = function () {
  94168. var engine = this._scene.getEngine();
  94169. // Indices
  94170. var indices = [];
  94171. indices.push(0);
  94172. indices.push(1);
  94173. indices.push(2);
  94174. indices.push(0);
  94175. indices.push(2);
  94176. indices.push(3);
  94177. this._indexBuffer = engine.createIndexBuffer(indices);
  94178. };
  94179. Layer.prototype._rebuild = function () {
  94180. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94181. if (vb) {
  94182. vb._rebuild();
  94183. }
  94184. this._createIndexBuffer();
  94185. };
  94186. Layer.prototype.render = function () {
  94187. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94188. // Check
  94189. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94190. return;
  94191. var engine = this._scene.getEngine();
  94192. this.onBeforeRenderObservable.notifyObservers(this);
  94193. // Render
  94194. engine.enableEffect(currentEffect);
  94195. engine.setState(false);
  94196. // Texture
  94197. currentEffect.setTexture("textureSampler", this.texture);
  94198. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94199. // Color
  94200. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94201. // Scale / offset
  94202. currentEffect.setVector2("offset", this.offset);
  94203. currentEffect.setVector2("scale", this.scale);
  94204. // VBOs
  94205. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94206. // Draw order
  94207. if (!this.alphaTest) {
  94208. engine.setAlphaMode(this.alphaBlendingMode);
  94209. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94210. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94211. }
  94212. else {
  94213. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94214. }
  94215. this.onAfterRenderObservable.notifyObservers(this);
  94216. };
  94217. Layer.prototype.dispose = function () {
  94218. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94219. if (vertexBuffer) {
  94220. vertexBuffer.dispose();
  94221. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94222. }
  94223. if (this._indexBuffer) {
  94224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94225. this._indexBuffer = null;
  94226. }
  94227. if (this.texture) {
  94228. this.texture.dispose();
  94229. this.texture = null;
  94230. }
  94231. // Remove from scene
  94232. var index = this._scene.layers.indexOf(this);
  94233. this._scene.layers.splice(index, 1);
  94234. // Callback
  94235. this.onDisposeObservable.notifyObservers(this);
  94236. this.onDisposeObservable.clear();
  94237. this.onAfterRenderObservable.clear();
  94238. this.onBeforeRenderObservable.clear();
  94239. };
  94240. return Layer;
  94241. }());
  94242. BABYLON.Layer = Layer;
  94243. })(BABYLON || (BABYLON = {}));
  94244. //# sourceMappingURL=babylon.layer.js.map
  94245. var BABYLON;
  94246. (function (BABYLON) {
  94247. var TextureTools = /** @class */ (function () {
  94248. function TextureTools() {
  94249. }
  94250. /**
  94251. * Uses the GPU to create a copy texture rescaled at a given size
  94252. * @param texture Texture to copy from
  94253. * @param width Desired width
  94254. * @param height Desired height
  94255. * @return Generated texture
  94256. */
  94257. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94258. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94259. var scene = texture.getScene();
  94260. var engine = scene.getEngine();
  94261. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94262. rtt.wrapU = texture.wrapU;
  94263. rtt.wrapV = texture.wrapV;
  94264. rtt.uOffset = texture.uOffset;
  94265. rtt.vOffset = texture.vOffset;
  94266. rtt.uScale = texture.uScale;
  94267. rtt.vScale = texture.vScale;
  94268. rtt.uAng = texture.uAng;
  94269. rtt.vAng = texture.vAng;
  94270. rtt.wAng = texture.wAng;
  94271. rtt.coordinatesIndex = texture.coordinatesIndex;
  94272. rtt.level = texture.level;
  94273. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94274. rtt._texture.isReady = false;
  94275. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94276. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94277. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94278. passPostProcess.getEffect().executeWhenCompiled(function () {
  94279. passPostProcess.onApply = function (effect) {
  94280. effect.setTexture("textureSampler", texture);
  94281. };
  94282. var internalTexture = rtt.getInternalTexture();
  94283. if (internalTexture) {
  94284. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94285. engine.unBindFramebuffer(internalTexture);
  94286. rtt.disposeFramebufferObjects();
  94287. passPostProcess.dispose();
  94288. internalTexture.isReady = true;
  94289. }
  94290. });
  94291. return rtt;
  94292. };
  94293. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94294. if (!scene._environmentBRDFTexture) {
  94295. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94296. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94297. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94298. scene._environmentBRDFTexture = texture;
  94299. }
  94300. return scene._environmentBRDFTexture;
  94301. };
  94302. 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=";
  94303. return TextureTools;
  94304. }());
  94305. BABYLON.TextureTools = TextureTools;
  94306. })(BABYLON || (BABYLON = {}));
  94307. //# sourceMappingURL=babylon.textureTools.js.map
  94308. var BABYLON;
  94309. (function (BABYLON) {
  94310. var FramingBehavior = /** @class */ (function () {
  94311. function FramingBehavior() {
  94312. this._mode = FramingBehavior.FitFrustumSidesMode;
  94313. this._radiusScale = 1.0;
  94314. this._positionScale = 0.5;
  94315. this._defaultElevation = 0.3;
  94316. this._elevationReturnTime = 1500;
  94317. this._elevationReturnWaitTime = 1000;
  94318. this._zoomStopsAnimation = false;
  94319. this._framingTime = 1500;
  94320. this._isPointerDown = false;
  94321. this._lastInteractionTime = -Infinity;
  94322. // Framing control
  94323. this._animatables = new Array();
  94324. this._betaIsAnimating = false;
  94325. }
  94326. Object.defineProperty(FramingBehavior.prototype, "name", {
  94327. get: function () {
  94328. return "Framing";
  94329. },
  94330. enumerable: true,
  94331. configurable: true
  94332. });
  94333. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94334. /**
  94335. * Gets current mode used by the behavior.
  94336. */
  94337. get: function () {
  94338. return this._mode;
  94339. },
  94340. /**
  94341. * Sets the current mode used by the behavior
  94342. */
  94343. set: function (mode) {
  94344. this._mode = mode;
  94345. },
  94346. enumerable: true,
  94347. configurable: true
  94348. });
  94349. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94350. /**
  94351. * Gets the scale applied to the radius
  94352. */
  94353. get: function () {
  94354. return this._radiusScale;
  94355. },
  94356. /**
  94357. * Sets the scale applied to the radius (1 by default)
  94358. */
  94359. set: function (radius) {
  94360. this._radiusScale = radius;
  94361. },
  94362. enumerable: true,
  94363. configurable: true
  94364. });
  94365. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94366. /**
  94367. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94368. */
  94369. get: function () {
  94370. return this._positionScale;
  94371. },
  94372. /**
  94373. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94374. */
  94375. set: function (scale) {
  94376. this._positionScale = scale;
  94377. },
  94378. enumerable: true,
  94379. configurable: true
  94380. });
  94381. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94382. /**
  94383. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94384. * behaviour is triggered, in radians.
  94385. */
  94386. get: function () {
  94387. return this._defaultElevation;
  94388. },
  94389. /**
  94390. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94391. * behaviour is triggered, in radians.
  94392. */
  94393. set: function (elevation) {
  94394. this._defaultElevation = elevation;
  94395. },
  94396. enumerable: true,
  94397. configurable: true
  94398. });
  94399. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94400. /**
  94401. * Gets the time (in milliseconds) taken to return to the default beta position.
  94402. * Negative value indicates camera should not return to default.
  94403. */
  94404. get: function () {
  94405. return this._elevationReturnTime;
  94406. },
  94407. /**
  94408. * Sets the time (in milliseconds) taken to return to the default beta position.
  94409. * Negative value indicates camera should not return to default.
  94410. */
  94411. set: function (speed) {
  94412. this._elevationReturnTime = speed;
  94413. },
  94414. enumerable: true,
  94415. configurable: true
  94416. });
  94417. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94418. /**
  94419. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94420. */
  94421. get: function () {
  94422. return this._elevationReturnWaitTime;
  94423. },
  94424. /**
  94425. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94426. */
  94427. set: function (time) {
  94428. this._elevationReturnWaitTime = time;
  94429. },
  94430. enumerable: true,
  94431. configurable: true
  94432. });
  94433. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94434. /**
  94435. * Gets the flag that indicates if user zooming should stop animation.
  94436. */
  94437. get: function () {
  94438. return this._zoomStopsAnimation;
  94439. },
  94440. /**
  94441. * Sets the flag that indicates if user zooming should stop animation.
  94442. */
  94443. set: function (flag) {
  94444. this._zoomStopsAnimation = flag;
  94445. },
  94446. enumerable: true,
  94447. configurable: true
  94448. });
  94449. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94450. /**
  94451. * Gets the transition time when framing the mesh, in milliseconds
  94452. */
  94453. get: function () {
  94454. return this._framingTime;
  94455. },
  94456. /**
  94457. * Sets the transition time when framing the mesh, in milliseconds
  94458. */
  94459. set: function (time) {
  94460. this._framingTime = time;
  94461. },
  94462. enumerable: true,
  94463. configurable: true
  94464. });
  94465. FramingBehavior.prototype.init = function () {
  94466. // Do notihng
  94467. };
  94468. FramingBehavior.prototype.attach = function (camera) {
  94469. var _this = this;
  94470. this._attachedCamera = camera;
  94471. var scene = this._attachedCamera.getScene();
  94472. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94473. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94474. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94475. _this._isPointerDown = true;
  94476. return;
  94477. }
  94478. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94479. _this._isPointerDown = false;
  94480. }
  94481. });
  94482. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94483. if (mesh) {
  94484. _this.zoomOnMesh(mesh);
  94485. }
  94486. });
  94487. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94488. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94489. _this._applyUserInteraction();
  94490. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94491. // back to the default position after a given timeout
  94492. _this._maintainCameraAboveGround();
  94493. });
  94494. };
  94495. FramingBehavior.prototype.detach = function () {
  94496. if (!this._attachedCamera) {
  94497. return;
  94498. }
  94499. var scene = this._attachedCamera.getScene();
  94500. if (this._onPrePointerObservableObserver) {
  94501. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94502. }
  94503. if (this._onAfterCheckInputsObserver) {
  94504. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94505. }
  94506. if (this._onMeshTargetChangedObserver) {
  94507. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94508. }
  94509. this._attachedCamera = null;
  94510. };
  94511. /**
  94512. * Targets the given mesh and updates zoom level accordingly.
  94513. * @param mesh The mesh to target.
  94514. * @param radius Optional. If a cached radius position already exists, overrides default.
  94515. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94516. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94517. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94518. */
  94519. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94520. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94521. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94522. mesh.computeWorldMatrix(true);
  94523. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94524. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94525. };
  94526. /**
  94527. * Targets the given mesh with its children and updates zoom level accordingly.
  94528. * @param mesh The mesh to target.
  94529. * @param radius Optional. If a cached radius position already exists, overrides default.
  94530. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94531. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94532. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94533. */
  94534. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94535. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94536. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94537. mesh.computeWorldMatrix(true);
  94538. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94539. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94540. };
  94541. /**
  94542. * Targets the given meshes with their children and updates zoom level accordingly.
  94543. * @param meshes The mesh to target.
  94544. * @param radius Optional. If a cached radius position already exists, overrides default.
  94545. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94546. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94547. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94548. */
  94549. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94550. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94551. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94552. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94553. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94554. for (var i = 0; i < meshes.length; i++) {
  94555. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94556. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94557. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94558. }
  94559. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94560. };
  94561. /**
  94562. * Targets the given mesh and updates zoom level accordingly.
  94563. * @param mesh The mesh to target.
  94564. * @param radius Optional. If a cached radius position already exists, overrides default.
  94565. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94566. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94567. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94568. */
  94569. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94570. var _this = this;
  94571. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94572. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94573. var zoomTarget;
  94574. if (!this._attachedCamera) {
  94575. return;
  94576. }
  94577. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94578. var bottom = minimumWorld.y;
  94579. var top = maximumWorld.y;
  94580. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94581. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94582. if (focusOnOriginXZ) {
  94583. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94584. }
  94585. else {
  94586. var centerWorld = minimumWorld.add(radiusWorld);
  94587. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94588. }
  94589. if (!this._vectorTransition) {
  94590. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94591. }
  94592. this._betaIsAnimating = true;
  94593. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94594. if (animatable) {
  94595. this._animatables.push(animatable);
  94596. }
  94597. // sets the radius and lower radius bounds
  94598. // Small delta ensures camera is not always at lower zoom limit.
  94599. var radius = 0;
  94600. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94601. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94602. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94603. radius = position;
  94604. }
  94605. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94606. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94607. if (this._attachedCamera.lowerRadiusLimit === null) {
  94608. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94609. }
  94610. }
  94611. // Set sensibilities
  94612. var extend = maximumWorld.subtract(minimumWorld).length();
  94613. this._attachedCamera.panningSensibility = 5000 / extend;
  94614. this._attachedCamera.wheelPrecision = 100 / radius;
  94615. // transition to new radius
  94616. if (!this._radiusTransition) {
  94617. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94618. }
  94619. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94620. _this.stopAllAnimations();
  94621. if (onAnimationEnd) {
  94622. onAnimationEnd();
  94623. }
  94624. if (_this._attachedCamera) {
  94625. _this._attachedCamera.storeState();
  94626. }
  94627. });
  94628. if (animatable) {
  94629. this._animatables.push(animatable);
  94630. }
  94631. };
  94632. /**
  94633. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94634. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94635. * frustum width.
  94636. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94637. * to fully enclose the mesh in the viewing frustum.
  94638. */
  94639. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94640. var size = maximumWorld.subtract(minimumWorld);
  94641. var boxVectorGlobalDiagonal = size.length();
  94642. var frustumSlope = this._getFrustumSlope();
  94643. // Formula for setting distance
  94644. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94645. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94646. // Horizon distance
  94647. var radius = radiusWithoutFraming * this._radiusScale;
  94648. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94649. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94650. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94651. var camera = this._attachedCamera;
  94652. if (!camera) {
  94653. return 0;
  94654. }
  94655. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94656. // Don't exceed the requested limit
  94657. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94658. }
  94659. // Don't exceed the upper radius limit
  94660. if (camera.upperRadiusLimit) {
  94661. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94662. }
  94663. return distance;
  94664. };
  94665. /**
  94666. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94667. * is automatically returned to its default position (expected to be above ground plane).
  94668. */
  94669. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94670. var _this = this;
  94671. if (this._elevationReturnTime < 0) {
  94672. return;
  94673. }
  94674. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94675. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94676. var limitBeta = Math.PI * 0.5;
  94677. // Bring the camera back up if below the ground plane
  94678. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94679. this._betaIsAnimating = true;
  94680. //Transition to new position
  94681. this.stopAllAnimations();
  94682. if (!this._betaTransition) {
  94683. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94684. }
  94685. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94686. _this._clearAnimationLocks();
  94687. _this.stopAllAnimations();
  94688. });
  94689. if (animatabe) {
  94690. this._animatables.push(animatabe);
  94691. }
  94692. }
  94693. };
  94694. /**
  94695. * Returns the frustum slope based on the canvas ratio and camera FOV
  94696. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94697. */
  94698. FramingBehavior.prototype._getFrustumSlope = function () {
  94699. // Calculate the viewport ratio
  94700. // Aspect Ratio is Height/Width.
  94701. var camera = this._attachedCamera;
  94702. if (!camera) {
  94703. return BABYLON.Vector2.Zero();
  94704. }
  94705. var engine = camera.getScene().getEngine();
  94706. var aspectRatio = engine.getAspectRatio(camera);
  94707. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94708. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94709. var frustumSlopeY = Math.tan(camera.fov / 2);
  94710. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94711. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94712. // along the forward vector.
  94713. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94714. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94715. };
  94716. /**
  94717. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94718. */
  94719. FramingBehavior.prototype._clearAnimationLocks = function () {
  94720. this._betaIsAnimating = false;
  94721. };
  94722. /**
  94723. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94724. */
  94725. FramingBehavior.prototype._applyUserInteraction = function () {
  94726. if (this.isUserIsMoving) {
  94727. this._lastInteractionTime = BABYLON.Tools.Now;
  94728. this.stopAllAnimations();
  94729. this._clearAnimationLocks();
  94730. }
  94731. };
  94732. /**
  94733. * Stops and removes all animations that have been applied to the camera
  94734. */
  94735. FramingBehavior.prototype.stopAllAnimations = function () {
  94736. if (this._attachedCamera) {
  94737. this._attachedCamera.animations = [];
  94738. }
  94739. while (this._animatables.length) {
  94740. if (this._animatables[0]) {
  94741. this._animatables[0].onAnimationEnd = null;
  94742. this._animatables[0].stop();
  94743. }
  94744. this._animatables.shift();
  94745. }
  94746. };
  94747. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94748. /**
  94749. * Gets a value indicating if the user is moving the camera
  94750. */
  94751. get: function () {
  94752. if (!this._attachedCamera) {
  94753. return false;
  94754. }
  94755. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94756. this._attachedCamera.inertialBetaOffset !== 0 ||
  94757. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94758. this._attachedCamera.inertialPanningX !== 0 ||
  94759. this._attachedCamera.inertialPanningY !== 0 ||
  94760. this._isPointerDown;
  94761. },
  94762. enumerable: true,
  94763. configurable: true
  94764. });
  94765. /**
  94766. * The easing function used by animations
  94767. */
  94768. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94769. /**
  94770. * The easing mode used by animations
  94771. */
  94772. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94773. // Statics
  94774. /**
  94775. * The camera can move all the way towards the mesh.
  94776. */
  94777. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94778. /**
  94779. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94780. */
  94781. FramingBehavior.FitFrustumSidesMode = 1;
  94782. return FramingBehavior;
  94783. }());
  94784. BABYLON.FramingBehavior = FramingBehavior;
  94785. })(BABYLON || (BABYLON = {}));
  94786. //# sourceMappingURL=babylon.framingBehavior.js.map
  94787. var BABYLON;
  94788. (function (BABYLON) {
  94789. /**
  94790. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94791. */
  94792. var BouncingBehavior = /** @class */ (function () {
  94793. function BouncingBehavior() {
  94794. /**
  94795. * The duration of the animation, in milliseconds
  94796. */
  94797. this.transitionDuration = 450;
  94798. /**
  94799. * Length of the distance animated by the transition when lower radius is reached
  94800. */
  94801. this.lowerRadiusTransitionRange = 2;
  94802. /**
  94803. * Length of the distance animated by the transition when upper radius is reached
  94804. */
  94805. this.upperRadiusTransitionRange = -2;
  94806. this._autoTransitionRange = false;
  94807. // Animations
  94808. this._radiusIsAnimating = false;
  94809. this._radiusBounceTransition = null;
  94810. this._animatables = new Array();
  94811. }
  94812. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94813. get: function () {
  94814. return "Bouncing";
  94815. },
  94816. enumerable: true,
  94817. configurable: true
  94818. });
  94819. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94820. /**
  94821. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94822. */
  94823. get: function () {
  94824. return this._autoTransitionRange;
  94825. },
  94826. /**
  94827. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94828. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94829. */
  94830. set: function (value) {
  94831. var _this = this;
  94832. if (this._autoTransitionRange === value) {
  94833. return;
  94834. }
  94835. this._autoTransitionRange = value;
  94836. var camera = this._attachedCamera;
  94837. if (!camera) {
  94838. return;
  94839. }
  94840. if (value) {
  94841. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94842. if (!mesh) {
  94843. return;
  94844. }
  94845. mesh.computeWorldMatrix(true);
  94846. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94847. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94848. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94849. });
  94850. }
  94851. else if (this._onMeshTargetChangedObserver) {
  94852. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94853. }
  94854. },
  94855. enumerable: true,
  94856. configurable: true
  94857. });
  94858. BouncingBehavior.prototype.init = function () {
  94859. // Do notihng
  94860. };
  94861. BouncingBehavior.prototype.attach = function (camera) {
  94862. var _this = this;
  94863. this._attachedCamera = camera;
  94864. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94865. if (!_this._attachedCamera) {
  94866. return;
  94867. }
  94868. // Add the bounce animation to the lower radius limit
  94869. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94870. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94871. }
  94872. // Add the bounce animation to the upper radius limit
  94873. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94874. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94875. }
  94876. });
  94877. };
  94878. BouncingBehavior.prototype.detach = function () {
  94879. if (!this._attachedCamera) {
  94880. return;
  94881. }
  94882. if (this._onAfterCheckInputsObserver) {
  94883. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94884. }
  94885. if (this._onMeshTargetChangedObserver) {
  94886. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94887. }
  94888. this._attachedCamera = null;
  94889. };
  94890. /**
  94891. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94892. * @param radiusLimit The limit to check against.
  94893. * @return Bool to indicate if at limit.
  94894. */
  94895. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94896. if (!this._attachedCamera) {
  94897. return false;
  94898. }
  94899. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94900. return true;
  94901. }
  94902. return false;
  94903. };
  94904. /**
  94905. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94906. * @param radiusDelta The delta by which to animate to. Can be negative.
  94907. */
  94908. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94909. var _this = this;
  94910. if (!this._attachedCamera) {
  94911. return;
  94912. }
  94913. if (!this._radiusBounceTransition) {
  94914. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94915. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94916. }
  94917. // Prevent zoom until bounce has completed
  94918. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94919. this._attachedCamera.wheelPrecision = Infinity;
  94920. this._attachedCamera.inertialRadiusOffset = 0;
  94921. // Animate to the radius limit
  94922. this.stopAllAnimations();
  94923. this._radiusIsAnimating = true;
  94924. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94925. if (animatable) {
  94926. this._animatables.push(animatable);
  94927. }
  94928. };
  94929. /**
  94930. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94931. */
  94932. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94933. this._radiusIsAnimating = false;
  94934. if (this._attachedCamera) {
  94935. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94936. }
  94937. };
  94938. /**
  94939. * Stops and removes all animations that have been applied to the camera
  94940. */
  94941. BouncingBehavior.prototype.stopAllAnimations = function () {
  94942. if (this._attachedCamera) {
  94943. this._attachedCamera.animations = [];
  94944. }
  94945. while (this._animatables.length) {
  94946. this._animatables[0].onAnimationEnd = null;
  94947. this._animatables[0].stop();
  94948. this._animatables.shift();
  94949. }
  94950. };
  94951. /**
  94952. * The easing function used by animations
  94953. */
  94954. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94955. /**
  94956. * The easing mode used by animations
  94957. */
  94958. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94959. return BouncingBehavior;
  94960. }());
  94961. BABYLON.BouncingBehavior = BouncingBehavior;
  94962. })(BABYLON || (BABYLON = {}));
  94963. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94964. var BABYLON;
  94965. (function (BABYLON) {
  94966. var AutoRotationBehavior = /** @class */ (function () {
  94967. function AutoRotationBehavior() {
  94968. this._zoomStopsAnimation = false;
  94969. this._idleRotationSpeed = 0.05;
  94970. this._idleRotationWaitTime = 2000;
  94971. this._idleRotationSpinupTime = 2000;
  94972. this._isPointerDown = false;
  94973. this._lastFrameTime = null;
  94974. this._lastInteractionTime = -Infinity;
  94975. this._cameraRotationSpeed = 0;
  94976. this._lastFrameRadius = 0;
  94977. }
  94978. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94979. get: function () {
  94980. return "AutoRotation";
  94981. },
  94982. enumerable: true,
  94983. configurable: true
  94984. });
  94985. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94986. /**
  94987. * Gets the flag that indicates if user zooming should stop animation.
  94988. */
  94989. get: function () {
  94990. return this._zoomStopsAnimation;
  94991. },
  94992. /**
  94993. * Sets the flag that indicates if user zooming should stop animation.
  94994. */
  94995. set: function (flag) {
  94996. this._zoomStopsAnimation = flag;
  94997. },
  94998. enumerable: true,
  94999. configurable: true
  95000. });
  95001. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95002. /**
  95003. * Gets the default speed at which the camera rotates around the model.
  95004. */
  95005. get: function () {
  95006. return this._idleRotationSpeed;
  95007. },
  95008. /**
  95009. * Sets the default speed at which the camera rotates around the model.
  95010. */
  95011. set: function (speed) {
  95012. this._idleRotationSpeed = speed;
  95013. },
  95014. enumerable: true,
  95015. configurable: true
  95016. });
  95017. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95018. /**
  95019. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95020. */
  95021. get: function () {
  95022. return this._idleRotationWaitTime;
  95023. },
  95024. /**
  95025. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95026. */
  95027. set: function (time) {
  95028. this._idleRotationWaitTime = time;
  95029. },
  95030. enumerable: true,
  95031. configurable: true
  95032. });
  95033. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95034. /**
  95035. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95036. */
  95037. get: function () {
  95038. return this._idleRotationSpinupTime;
  95039. },
  95040. /**
  95041. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95042. */
  95043. set: function (time) {
  95044. this._idleRotationSpinupTime = time;
  95045. },
  95046. enumerable: true,
  95047. configurable: true
  95048. });
  95049. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95050. /**
  95051. * Gets a value indicating if the camera is currently rotating because of this behavior
  95052. */
  95053. get: function () {
  95054. return Math.abs(this._cameraRotationSpeed) > 0;
  95055. },
  95056. enumerable: true,
  95057. configurable: true
  95058. });
  95059. AutoRotationBehavior.prototype.init = function () {
  95060. // Do notihng
  95061. };
  95062. AutoRotationBehavior.prototype.attach = function (camera) {
  95063. var _this = this;
  95064. this._attachedCamera = camera;
  95065. var scene = this._attachedCamera.getScene();
  95066. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95067. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95068. _this._isPointerDown = true;
  95069. return;
  95070. }
  95071. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95072. _this._isPointerDown = false;
  95073. }
  95074. });
  95075. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95076. var now = BABYLON.Tools.Now;
  95077. var dt = 0;
  95078. if (_this._lastFrameTime != null) {
  95079. dt = now - _this._lastFrameTime;
  95080. }
  95081. _this._lastFrameTime = now;
  95082. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95083. _this._applyUserInteraction();
  95084. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95085. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95086. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95087. // Step camera rotation by rotation speed
  95088. if (_this._attachedCamera) {
  95089. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95090. }
  95091. });
  95092. };
  95093. AutoRotationBehavior.prototype.detach = function () {
  95094. if (!this._attachedCamera) {
  95095. return;
  95096. }
  95097. var scene = this._attachedCamera.getScene();
  95098. if (this._onPrePointerObservableObserver) {
  95099. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95100. }
  95101. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95102. this._attachedCamera = null;
  95103. };
  95104. /**
  95105. * Returns true if user is scrolling.
  95106. * @return true if user is scrolling.
  95107. */
  95108. AutoRotationBehavior.prototype._userIsZooming = function () {
  95109. if (!this._attachedCamera) {
  95110. return false;
  95111. }
  95112. return this._attachedCamera.inertialRadiusOffset !== 0;
  95113. };
  95114. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95115. if (!this._attachedCamera) {
  95116. return false;
  95117. }
  95118. var zoomHasHitLimit = false;
  95119. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95120. zoomHasHitLimit = true;
  95121. }
  95122. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95123. this._lastFrameRadius = this._attachedCamera.radius;
  95124. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95125. };
  95126. /**
  95127. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95128. */
  95129. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95130. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95131. this._lastInteractionTime = BABYLON.Tools.Now;
  95132. }
  95133. };
  95134. // Tools
  95135. AutoRotationBehavior.prototype._userIsMoving = function () {
  95136. if (!this._attachedCamera) {
  95137. return false;
  95138. }
  95139. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95140. this._attachedCamera.inertialBetaOffset !== 0 ||
  95141. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95142. this._attachedCamera.inertialPanningX !== 0 ||
  95143. this._attachedCamera.inertialPanningY !== 0 ||
  95144. this._isPointerDown;
  95145. };
  95146. return AutoRotationBehavior;
  95147. }());
  95148. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95149. })(BABYLON || (BABYLON = {}));
  95150. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95151. var BABYLON;
  95152. (function (BABYLON) {
  95153. var NullEngineOptions = /** @class */ (function () {
  95154. function NullEngineOptions() {
  95155. this.renderWidth = 512;
  95156. this.renderHeight = 256;
  95157. this.textureSize = 512;
  95158. this.deterministicLockstep = false;
  95159. this.lockstepMaxSteps = 4;
  95160. }
  95161. return NullEngineOptions;
  95162. }());
  95163. BABYLON.NullEngineOptions = NullEngineOptions;
  95164. /**
  95165. * The null engine class provides support for headless version of babylon.js.
  95166. * This can be used in server side scenario or for testing purposes
  95167. */
  95168. var NullEngine = /** @class */ (function (_super) {
  95169. __extends(NullEngine, _super);
  95170. function NullEngine(options) {
  95171. if (options === void 0) { options = new NullEngineOptions(); }
  95172. var _this = _super.call(this, null) || this;
  95173. if (options.deterministicLockstep === undefined) {
  95174. options.deterministicLockstep = false;
  95175. }
  95176. if (options.lockstepMaxSteps === undefined) {
  95177. options.lockstepMaxSteps = 4;
  95178. }
  95179. _this._options = options;
  95180. // Init caps
  95181. // We consider we are on a webgl1 capable device
  95182. _this._caps = new BABYLON.EngineCapabilities();
  95183. _this._caps.maxTexturesImageUnits = 16;
  95184. _this._caps.maxVertexTextureImageUnits = 16;
  95185. _this._caps.maxTextureSize = 512;
  95186. _this._caps.maxCubemapTextureSize = 512;
  95187. _this._caps.maxRenderTextureSize = 512;
  95188. _this._caps.maxVertexAttribs = 16;
  95189. _this._caps.maxVaryingVectors = 16;
  95190. _this._caps.maxFragmentUniformVectors = 16;
  95191. _this._caps.maxVertexUniformVectors = 16;
  95192. // Extensions
  95193. _this._caps.standardDerivatives = false;
  95194. _this._caps.astc = null;
  95195. _this._caps.s3tc = null;
  95196. _this._caps.pvrtc = null;
  95197. _this._caps.etc1 = null;
  95198. _this._caps.etc2 = null;
  95199. _this._caps.textureAnisotropicFilterExtension = null;
  95200. _this._caps.maxAnisotropy = 0;
  95201. _this._caps.uintIndices = false;
  95202. _this._caps.fragmentDepthSupported = false;
  95203. _this._caps.highPrecisionShaderSupported = true;
  95204. _this._caps.colorBufferFloat = false;
  95205. _this._caps.textureFloat = false;
  95206. _this._caps.textureFloatLinearFiltering = false;
  95207. _this._caps.textureFloatRender = false;
  95208. _this._caps.textureHalfFloat = false;
  95209. _this._caps.textureHalfFloatLinearFiltering = false;
  95210. _this._caps.textureHalfFloatRender = false;
  95211. _this._caps.textureLOD = false;
  95212. _this._caps.drawBuffersExtension = false;
  95213. _this._caps.depthTextureExtension = false;
  95214. _this._caps.vertexArrayObject = false;
  95215. _this._caps.instancedArrays = false;
  95216. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95217. // Wrappers
  95218. if (typeof URL === "undefined") {
  95219. URL = {
  95220. createObjectURL: function () { },
  95221. revokeObjectURL: function () { }
  95222. };
  95223. }
  95224. if (typeof Blob === "undefined") {
  95225. Blob = function () { };
  95226. }
  95227. return _this;
  95228. }
  95229. NullEngine.prototype.isDeterministicLockStep = function () {
  95230. return this._options.deterministicLockstep;
  95231. };
  95232. NullEngine.prototype.getLockstepMaxSteps = function () {
  95233. return this._options.lockstepMaxSteps;
  95234. };
  95235. NullEngine.prototype.getHardwareScalingLevel = function () {
  95236. return 1.0;
  95237. };
  95238. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95239. return {
  95240. capacity: 0,
  95241. references: 1,
  95242. is32Bits: false
  95243. };
  95244. };
  95245. NullEngine.prototype.createIndexBuffer = function (indices) {
  95246. return {
  95247. capacity: 0,
  95248. references: 1,
  95249. is32Bits: false
  95250. };
  95251. };
  95252. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95253. if (stencil === void 0) { stencil = false; }
  95254. };
  95255. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95256. if (useScreen === void 0) { useScreen = false; }
  95257. if (!useScreen && this._currentRenderTarget) {
  95258. return this._currentRenderTarget.width;
  95259. }
  95260. return this._options.renderWidth;
  95261. };
  95262. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95263. if (useScreen === void 0) { useScreen = false; }
  95264. if (!useScreen && this._currentRenderTarget) {
  95265. return this._currentRenderTarget.height;
  95266. }
  95267. return this._options.renderHeight;
  95268. };
  95269. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95270. this._cachedViewport = viewport;
  95271. };
  95272. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95273. return {
  95274. transformFeedback: null,
  95275. __SPECTOR_rebuildProgram: null
  95276. };
  95277. };
  95278. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95279. return [];
  95280. };
  95281. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95282. return [];
  95283. };
  95284. NullEngine.prototype.bindSamplers = function (effect) {
  95285. this._currentEffect = null;
  95286. };
  95287. NullEngine.prototype.enableEffect = function (effect) {
  95288. this._currentEffect = effect;
  95289. if (effect.onBind) {
  95290. effect.onBind(effect);
  95291. }
  95292. effect.onBindObservable.notifyObservers(effect);
  95293. };
  95294. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95295. if (zOffset === void 0) { zOffset = 0; }
  95296. if (reverseSide === void 0) { reverseSide = false; }
  95297. };
  95298. NullEngine.prototype.setIntArray = function (uniform, array) {
  95299. };
  95300. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95301. };
  95302. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95303. };
  95304. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95305. };
  95306. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95307. };
  95308. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95309. };
  95310. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95311. };
  95312. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95313. };
  95314. NullEngine.prototype.setArray = function (uniform, array) {
  95315. };
  95316. NullEngine.prototype.setArray2 = function (uniform, array) {
  95317. };
  95318. NullEngine.prototype.setArray3 = function (uniform, array) {
  95319. };
  95320. NullEngine.prototype.setArray4 = function (uniform, array) {
  95321. };
  95322. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95323. };
  95324. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95325. };
  95326. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95327. };
  95328. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95329. };
  95330. NullEngine.prototype.setFloat = function (uniform, value) {
  95331. };
  95332. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95333. };
  95334. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95335. };
  95336. NullEngine.prototype.setBool = function (uniform, bool) {
  95337. };
  95338. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95339. };
  95340. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95341. };
  95342. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95343. };
  95344. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95345. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95346. if (this._alphaMode === mode) {
  95347. return;
  95348. }
  95349. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95350. if (!noDepthWriteChange) {
  95351. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95352. }
  95353. this._alphaMode = mode;
  95354. };
  95355. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95356. };
  95357. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95358. if (this.preventCacheWipeBetweenFrames) {
  95359. return;
  95360. }
  95361. this.resetTextureCache();
  95362. this._currentEffect = null;
  95363. if (bruteForce) {
  95364. this._currentProgram = null;
  95365. this._stencilState.reset();
  95366. this._depthCullingState.reset();
  95367. this._alphaState.reset();
  95368. }
  95369. this._cachedVertexBuffers = null;
  95370. this._cachedIndexBuffer = null;
  95371. this._cachedEffectForVertexBuffers = null;
  95372. };
  95373. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95374. };
  95375. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95376. };
  95377. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95378. };
  95379. NullEngine.prototype._createTexture = function () {
  95380. return {};
  95381. };
  95382. NullEngine.prototype._releaseTexture = function (texture) {
  95383. };
  95384. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95386. if (onLoad === void 0) { onLoad = null; }
  95387. if (onError === void 0) { onError = null; }
  95388. if (buffer === void 0) { buffer = null; }
  95389. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95390. var url = String(urlArg);
  95391. texture.url = url;
  95392. texture.generateMipMaps = !noMipmap;
  95393. texture.samplingMode = samplingMode;
  95394. texture.invertY = invertY;
  95395. texture.baseWidth = this._options.textureSize;
  95396. texture.baseHeight = this._options.textureSize;
  95397. texture.width = this._options.textureSize;
  95398. texture.height = this._options.textureSize;
  95399. if (format) {
  95400. texture.format = format;
  95401. }
  95402. texture.isReady = true;
  95403. if (onLoad) {
  95404. onLoad();
  95405. }
  95406. this._internalTexturesCache.push(texture);
  95407. return texture;
  95408. };
  95409. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95410. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95411. if (options !== undefined && typeof options === "object") {
  95412. fullOptions.generateMipMaps = options.generateMipMaps;
  95413. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95414. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95415. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95416. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95417. }
  95418. else {
  95419. fullOptions.generateMipMaps = options;
  95420. fullOptions.generateDepthBuffer = true;
  95421. fullOptions.generateStencilBuffer = false;
  95422. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95423. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95424. }
  95425. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95426. var width = size.width || size;
  95427. var height = size.height || size;
  95428. texture._depthStencilBuffer = {};
  95429. texture._framebuffer = {};
  95430. texture.baseWidth = width;
  95431. texture.baseHeight = height;
  95432. texture.width = width;
  95433. texture.height = height;
  95434. texture.isReady = true;
  95435. texture.samples = 1;
  95436. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95437. texture.samplingMode = fullOptions.samplingMode;
  95438. texture.type = fullOptions.type;
  95439. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95440. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95441. this._internalTexturesCache.push(texture);
  95442. return texture;
  95443. };
  95444. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95445. texture.samplingMode = samplingMode;
  95446. };
  95447. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95448. if (this._currentRenderTarget) {
  95449. this.unBindFramebuffer(this._currentRenderTarget);
  95450. }
  95451. this._currentRenderTarget = texture;
  95452. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95453. if (this._cachedViewport && !forceFullscreenViewport) {
  95454. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95455. }
  95456. };
  95457. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95458. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95459. this._currentRenderTarget = null;
  95460. if (onBeforeUnbind) {
  95461. if (texture._MSAAFramebuffer) {
  95462. this._currentFramebuffer = texture._framebuffer;
  95463. }
  95464. onBeforeUnbind();
  95465. }
  95466. this._currentFramebuffer = null;
  95467. };
  95468. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95469. var vbo = {
  95470. capacity: 1,
  95471. references: 1,
  95472. is32Bits: false
  95473. };
  95474. return vbo;
  95475. };
  95476. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95477. if (offset === void 0) { offset = 0; }
  95478. };
  95479. /**
  95480. * Updates a dynamic vertex buffer.
  95481. * @param vertexBuffer the vertex buffer to update
  95482. * @param data the data used to update the vertex buffer
  95483. * @param byteOffset the byte offset of the data (optional)
  95484. * @param byteLength the byte length of the data (optional)
  95485. */
  95486. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95487. };
  95488. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95489. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95490. this._boundTexturesCache[this._activeChannel] = texture;
  95491. }
  95492. };
  95493. NullEngine.prototype._bindTexture = function (channel, texture) {
  95494. if (channel < 0) {
  95495. return;
  95496. }
  95497. this._bindTextureDirectly(0, texture);
  95498. };
  95499. NullEngine.prototype._releaseBuffer = function (buffer) {
  95500. buffer.references--;
  95501. if (buffer.references === 0) {
  95502. return true;
  95503. }
  95504. return false;
  95505. };
  95506. NullEngine.prototype.releaseEffects = function () {
  95507. };
  95508. return NullEngine;
  95509. }(BABYLON.Engine));
  95510. BABYLON.NullEngine = NullEngine;
  95511. })(BABYLON || (BABYLON = {}));
  95512. //# sourceMappingURL=babylon.nullEngine.js.map
  95513. var BABYLON;
  95514. (function (BABYLON) {
  95515. /**
  95516. * This class can be used to get instrumentation data from a Babylon engine
  95517. */
  95518. var EngineInstrumentation = /** @class */ (function () {
  95519. function EngineInstrumentation(engine) {
  95520. this.engine = engine;
  95521. this._captureGPUFrameTime = false;
  95522. this._gpuFrameTime = new BABYLON.PerfCounter();
  95523. this._captureShaderCompilationTime = false;
  95524. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95525. // Observers
  95526. this._onBeginFrameObserver = null;
  95527. this._onEndFrameObserver = null;
  95528. this._onBeforeShaderCompilationObserver = null;
  95529. this._onAfterShaderCompilationObserver = null;
  95530. }
  95531. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95532. // Properties
  95533. /**
  95534. * Gets the perf counter used for GPU frame time
  95535. */
  95536. get: function () {
  95537. return this._gpuFrameTime;
  95538. },
  95539. enumerable: true,
  95540. configurable: true
  95541. });
  95542. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95543. /**
  95544. * Gets the GPU frame time capture status
  95545. */
  95546. get: function () {
  95547. return this._captureGPUFrameTime;
  95548. },
  95549. /**
  95550. * Enable or disable the GPU frame time capture
  95551. */
  95552. set: function (value) {
  95553. var _this = this;
  95554. if (value === this._captureGPUFrameTime) {
  95555. return;
  95556. }
  95557. this._captureGPUFrameTime = value;
  95558. if (value) {
  95559. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95560. if (!_this._gpuFrameTimeToken) {
  95561. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95562. }
  95563. });
  95564. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95565. if (!_this._gpuFrameTimeToken) {
  95566. return;
  95567. }
  95568. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95569. if (time > -1) {
  95570. _this._gpuFrameTimeToken = null;
  95571. _this._gpuFrameTime.fetchNewFrame();
  95572. _this._gpuFrameTime.addCount(time, true);
  95573. }
  95574. });
  95575. }
  95576. else {
  95577. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95578. this._onBeginFrameObserver = null;
  95579. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95580. this._onEndFrameObserver = null;
  95581. }
  95582. },
  95583. enumerable: true,
  95584. configurable: true
  95585. });
  95586. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95587. /**
  95588. * Gets the perf counter used for shader compilation time
  95589. */
  95590. get: function () {
  95591. return this._shaderCompilationTime;
  95592. },
  95593. enumerable: true,
  95594. configurable: true
  95595. });
  95596. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95597. /**
  95598. * Gets the shader compilation time capture status
  95599. */
  95600. get: function () {
  95601. return this._captureShaderCompilationTime;
  95602. },
  95603. /**
  95604. * Enable or disable the shader compilation time capture
  95605. */
  95606. set: function (value) {
  95607. var _this = this;
  95608. if (value === this._captureShaderCompilationTime) {
  95609. return;
  95610. }
  95611. this._captureShaderCompilationTime = value;
  95612. if (value) {
  95613. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95614. _this._shaderCompilationTime.fetchNewFrame();
  95615. _this._shaderCompilationTime.beginMonitoring();
  95616. });
  95617. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95618. _this._shaderCompilationTime.endMonitoring();
  95619. });
  95620. }
  95621. else {
  95622. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95623. this._onBeforeShaderCompilationObserver = null;
  95624. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95625. this._onAfterShaderCompilationObserver = null;
  95626. }
  95627. },
  95628. enumerable: true,
  95629. configurable: true
  95630. });
  95631. EngineInstrumentation.prototype.dispose = function () {
  95632. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95633. this._onBeginFrameObserver = null;
  95634. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95635. this._onEndFrameObserver = null;
  95636. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95637. this._onBeforeShaderCompilationObserver = null;
  95638. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95639. this._onAfterShaderCompilationObserver = null;
  95640. this.engine = null;
  95641. };
  95642. return EngineInstrumentation;
  95643. }());
  95644. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95645. })(BABYLON || (BABYLON = {}));
  95646. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95647. var BABYLON;
  95648. (function (BABYLON) {
  95649. /**
  95650. * This class can be used to get instrumentation data from a Babylon engine
  95651. */
  95652. var SceneInstrumentation = /** @class */ (function () {
  95653. function SceneInstrumentation(scene) {
  95654. var _this = this;
  95655. this.scene = scene;
  95656. this._captureActiveMeshesEvaluationTime = false;
  95657. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95658. this._captureRenderTargetsRenderTime = false;
  95659. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95660. this._captureFrameTime = false;
  95661. this._frameTime = new BABYLON.PerfCounter();
  95662. this._captureRenderTime = false;
  95663. this._renderTime = new BABYLON.PerfCounter();
  95664. this._captureInterFrameTime = false;
  95665. this._interFrameTime = new BABYLON.PerfCounter();
  95666. this._captureParticlesRenderTime = false;
  95667. this._particlesRenderTime = new BABYLON.PerfCounter();
  95668. this._captureSpritesRenderTime = false;
  95669. this._spritesRenderTime = new BABYLON.PerfCounter();
  95670. this._capturePhysicsTime = false;
  95671. this._physicsTime = new BABYLON.PerfCounter();
  95672. this._captureAnimationsTime = false;
  95673. this._animationsTime = new BABYLON.PerfCounter();
  95674. // Observers
  95675. this._onBeforeActiveMeshesEvaluationObserver = null;
  95676. this._onAfterActiveMeshesEvaluationObserver = null;
  95677. this._onBeforeRenderTargetsRenderObserver = null;
  95678. this._onAfterRenderTargetsRenderObserver = null;
  95679. this._onAfterRenderObserver = null;
  95680. this._onBeforeDrawPhaseObserver = null;
  95681. this._onAfterDrawPhaseObserver = null;
  95682. this._onBeforeAnimationsObserver = null;
  95683. this._onBeforeParticlesRenderingObserver = null;
  95684. this._onAfterParticlesRenderingObserver = null;
  95685. this._onBeforeSpritesRenderingObserver = null;
  95686. this._onAfterSpritesRenderingObserver = null;
  95687. this._onBeforePhysicsObserver = null;
  95688. this._onAfterPhysicsObserver = null;
  95689. this._onAfterAnimationsObserver = null;
  95690. // Before render
  95691. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95692. if (_this._captureActiveMeshesEvaluationTime) {
  95693. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95694. }
  95695. if (_this._captureRenderTargetsRenderTime) {
  95696. _this._renderTargetsRenderTime.fetchNewFrame();
  95697. }
  95698. if (_this._captureFrameTime) {
  95699. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95700. _this._frameTime.beginMonitoring();
  95701. }
  95702. if (_this._captureInterFrameTime) {
  95703. _this._interFrameTime.endMonitoring();
  95704. }
  95705. if (_this._captureParticlesRenderTime) {
  95706. _this._particlesRenderTime.fetchNewFrame();
  95707. }
  95708. if (_this._captureSpritesRenderTime) {
  95709. _this._spritesRenderTime.fetchNewFrame();
  95710. }
  95711. if (_this._captureAnimationsTime) {
  95712. _this._animationsTime.beginMonitoring();
  95713. }
  95714. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95715. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95716. });
  95717. // After render
  95718. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95719. if (_this._captureFrameTime) {
  95720. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95721. _this._frameTime.endMonitoring();
  95722. }
  95723. if (_this._captureRenderTime) {
  95724. _this._renderTime.endMonitoring(false);
  95725. }
  95726. if (_this._captureInterFrameTime) {
  95727. _this._interFrameTime.beginMonitoring();
  95728. }
  95729. });
  95730. }
  95731. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95732. // Properties
  95733. /**
  95734. * Gets the perf counter used for active meshes evaluation time
  95735. */
  95736. get: function () {
  95737. return this._activeMeshesEvaluationTime;
  95738. },
  95739. enumerable: true,
  95740. configurable: true
  95741. });
  95742. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95743. /**
  95744. * Gets the active meshes evaluation time capture status
  95745. */
  95746. get: function () {
  95747. return this._captureActiveMeshesEvaluationTime;
  95748. },
  95749. /**
  95750. * Enable or disable the active meshes evaluation time capture
  95751. */
  95752. set: function (value) {
  95753. var _this = this;
  95754. if (value === this._captureActiveMeshesEvaluationTime) {
  95755. return;
  95756. }
  95757. this._captureActiveMeshesEvaluationTime = value;
  95758. if (value) {
  95759. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95760. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95761. _this._activeMeshesEvaluationTime.beginMonitoring();
  95762. });
  95763. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95764. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95765. _this._activeMeshesEvaluationTime.endMonitoring();
  95766. });
  95767. }
  95768. else {
  95769. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95770. this._onBeforeActiveMeshesEvaluationObserver = null;
  95771. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95772. this._onAfterActiveMeshesEvaluationObserver = null;
  95773. }
  95774. },
  95775. enumerable: true,
  95776. configurable: true
  95777. });
  95778. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95779. /**
  95780. * Gets the perf counter used for render targets render time
  95781. */
  95782. get: function () {
  95783. return this._renderTargetsRenderTime;
  95784. },
  95785. enumerable: true,
  95786. configurable: true
  95787. });
  95788. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95789. /**
  95790. * Gets the render targets render time capture status
  95791. */
  95792. get: function () {
  95793. return this._captureRenderTargetsRenderTime;
  95794. },
  95795. /**
  95796. * Enable or disable the render targets render time capture
  95797. */
  95798. set: function (value) {
  95799. var _this = this;
  95800. if (value === this._captureRenderTargetsRenderTime) {
  95801. return;
  95802. }
  95803. this._captureRenderTargetsRenderTime = value;
  95804. if (value) {
  95805. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95806. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95807. _this._renderTargetsRenderTime.beginMonitoring();
  95808. });
  95809. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95810. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95811. _this._renderTargetsRenderTime.endMonitoring(false);
  95812. });
  95813. }
  95814. else {
  95815. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95816. this._onBeforeRenderTargetsRenderObserver = null;
  95817. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95818. this._onAfterRenderTargetsRenderObserver = null;
  95819. }
  95820. },
  95821. enumerable: true,
  95822. configurable: true
  95823. });
  95824. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95825. /**
  95826. * Gets the perf counter used for particles render time
  95827. */
  95828. get: function () {
  95829. return this._particlesRenderTime;
  95830. },
  95831. enumerable: true,
  95832. configurable: true
  95833. });
  95834. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95835. /**
  95836. * Gets the particles render time capture status
  95837. */
  95838. get: function () {
  95839. return this._captureParticlesRenderTime;
  95840. },
  95841. /**
  95842. * Enable or disable the particles render time capture
  95843. */
  95844. set: function (value) {
  95845. var _this = this;
  95846. if (value === this._captureParticlesRenderTime) {
  95847. return;
  95848. }
  95849. this._captureParticlesRenderTime = value;
  95850. if (value) {
  95851. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95852. BABYLON.Tools.StartPerformanceCounter("Particles");
  95853. _this._particlesRenderTime.beginMonitoring();
  95854. });
  95855. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95856. BABYLON.Tools.EndPerformanceCounter("Particles");
  95857. _this._particlesRenderTime.endMonitoring(false);
  95858. });
  95859. }
  95860. else {
  95861. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95862. this._onBeforeParticlesRenderingObserver = null;
  95863. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95864. this._onAfterParticlesRenderingObserver = null;
  95865. }
  95866. },
  95867. enumerable: true,
  95868. configurable: true
  95869. });
  95870. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95871. /**
  95872. * Gets the perf counter used for sprites render time
  95873. */
  95874. get: function () {
  95875. return this._spritesRenderTime;
  95876. },
  95877. enumerable: true,
  95878. configurable: true
  95879. });
  95880. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95881. /**
  95882. * Gets the sprites render time capture status
  95883. */
  95884. get: function () {
  95885. return this._captureSpritesRenderTime;
  95886. },
  95887. /**
  95888. * Enable or disable the sprites render time capture
  95889. */
  95890. set: function (value) {
  95891. var _this = this;
  95892. if (value === this._captureSpritesRenderTime) {
  95893. return;
  95894. }
  95895. this._captureSpritesRenderTime = value;
  95896. if (value) {
  95897. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95898. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95899. _this._spritesRenderTime.beginMonitoring();
  95900. });
  95901. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95902. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95903. _this._spritesRenderTime.endMonitoring(false);
  95904. });
  95905. }
  95906. else {
  95907. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95908. this._onBeforeSpritesRenderingObserver = null;
  95909. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95910. this._onAfterSpritesRenderingObserver = null;
  95911. }
  95912. },
  95913. enumerable: true,
  95914. configurable: true
  95915. });
  95916. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95917. /**
  95918. * Gets the perf counter used for physics time
  95919. */
  95920. get: function () {
  95921. return this._physicsTime;
  95922. },
  95923. enumerable: true,
  95924. configurable: true
  95925. });
  95926. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95927. /**
  95928. * Gets the physics time capture status
  95929. */
  95930. get: function () {
  95931. return this._capturePhysicsTime;
  95932. },
  95933. /**
  95934. * Enable or disable the physics time capture
  95935. */
  95936. set: function (value) {
  95937. var _this = this;
  95938. if (value === this._capturePhysicsTime) {
  95939. return;
  95940. }
  95941. this._capturePhysicsTime = value;
  95942. if (value) {
  95943. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95944. BABYLON.Tools.StartPerformanceCounter("Physics");
  95945. _this._physicsTime.beginMonitoring();
  95946. });
  95947. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95948. BABYLON.Tools.EndPerformanceCounter("Physics");
  95949. _this._physicsTime.endMonitoring();
  95950. });
  95951. }
  95952. else {
  95953. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95954. this._onBeforePhysicsObserver = null;
  95955. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95956. this._onAfterPhysicsObserver = null;
  95957. }
  95958. },
  95959. enumerable: true,
  95960. configurable: true
  95961. });
  95962. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95963. /**
  95964. * Gets the perf counter used for animations time
  95965. */
  95966. get: function () {
  95967. return this._animationsTime;
  95968. },
  95969. enumerable: true,
  95970. configurable: true
  95971. });
  95972. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95973. /**
  95974. * Gets the animations time capture status
  95975. */
  95976. get: function () {
  95977. return this._captureAnimationsTime;
  95978. },
  95979. /**
  95980. * Enable or disable the animations time capture
  95981. */
  95982. set: function (value) {
  95983. var _this = this;
  95984. if (value === this._captureAnimationsTime) {
  95985. return;
  95986. }
  95987. this._captureAnimationsTime = value;
  95988. if (value) {
  95989. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95990. _this._animationsTime.endMonitoring();
  95991. });
  95992. }
  95993. else {
  95994. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95995. this._onAfterAnimationsObserver = null;
  95996. }
  95997. },
  95998. enumerable: true,
  95999. configurable: true
  96000. });
  96001. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96002. /**
  96003. * Gets the perf counter used for frame time capture
  96004. */
  96005. get: function () {
  96006. return this._frameTime;
  96007. },
  96008. enumerable: true,
  96009. configurable: true
  96010. });
  96011. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96012. /**
  96013. * Gets the frame time capture status
  96014. */
  96015. get: function () {
  96016. return this._captureFrameTime;
  96017. },
  96018. /**
  96019. * Enable or disable the frame time capture
  96020. */
  96021. set: function (value) {
  96022. this._captureFrameTime = value;
  96023. },
  96024. enumerable: true,
  96025. configurable: true
  96026. });
  96027. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96028. /**
  96029. * Gets the perf counter used for inter-frames time capture
  96030. */
  96031. get: function () {
  96032. return this._interFrameTime;
  96033. },
  96034. enumerable: true,
  96035. configurable: true
  96036. });
  96037. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96038. /**
  96039. * Gets the inter-frames time capture status
  96040. */
  96041. get: function () {
  96042. return this._captureInterFrameTime;
  96043. },
  96044. /**
  96045. * Enable or disable the inter-frames time capture
  96046. */
  96047. set: function (value) {
  96048. this._captureInterFrameTime = value;
  96049. },
  96050. enumerable: true,
  96051. configurable: true
  96052. });
  96053. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96054. /**
  96055. * Gets the perf counter used for render time capture
  96056. */
  96057. get: function () {
  96058. return this._renderTime;
  96059. },
  96060. enumerable: true,
  96061. configurable: true
  96062. });
  96063. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96064. /**
  96065. * Gets the render time capture status
  96066. */
  96067. get: function () {
  96068. return this._captureRenderTime;
  96069. },
  96070. /**
  96071. * Enable or disable the render time capture
  96072. */
  96073. set: function (value) {
  96074. var _this = this;
  96075. if (value === this._captureRenderTime) {
  96076. return;
  96077. }
  96078. this._captureRenderTime = value;
  96079. if (value) {
  96080. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96081. _this._renderTime.beginMonitoring();
  96082. BABYLON.Tools.StartPerformanceCounter("Main render");
  96083. });
  96084. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96085. _this._renderTime.endMonitoring(false);
  96086. BABYLON.Tools.EndPerformanceCounter("Main render");
  96087. });
  96088. }
  96089. else {
  96090. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96091. this._onBeforeDrawPhaseObserver = null;
  96092. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96093. this._onAfterDrawPhaseObserver = null;
  96094. }
  96095. },
  96096. enumerable: true,
  96097. configurable: true
  96098. });
  96099. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96100. /**
  96101. * Gets the perf counter used for draw calls
  96102. */
  96103. get: function () {
  96104. return this.scene.getEngine()._drawCalls;
  96105. },
  96106. enumerable: true,
  96107. configurable: true
  96108. });
  96109. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96110. /**
  96111. * Gets the perf counter used for texture collisions
  96112. */
  96113. get: function () {
  96114. return this.scene.getEngine()._textureCollisions;
  96115. },
  96116. enumerable: true,
  96117. configurable: true
  96118. });
  96119. SceneInstrumentation.prototype.dispose = function () {
  96120. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96121. this._onAfterRenderObserver = null;
  96122. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96123. this._onBeforeActiveMeshesEvaluationObserver = null;
  96124. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96125. this._onAfterActiveMeshesEvaluationObserver = null;
  96126. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96127. this._onBeforeRenderTargetsRenderObserver = null;
  96128. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96129. this._onAfterRenderTargetsRenderObserver = null;
  96130. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96131. this._onBeforeAnimationsObserver = null;
  96132. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96133. this._onBeforeParticlesRenderingObserver = null;
  96134. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96135. this._onAfterParticlesRenderingObserver = null;
  96136. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96137. this._onBeforeSpritesRenderingObserver = null;
  96138. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96139. this._onAfterSpritesRenderingObserver = null;
  96140. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96141. this._onBeforeDrawPhaseObserver = null;
  96142. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96143. this._onAfterDrawPhaseObserver = null;
  96144. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96145. this._onBeforePhysicsObserver = null;
  96146. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96147. this._onAfterPhysicsObserver = null;
  96148. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96149. this._onAfterAnimationsObserver = null;
  96150. this.scene = null;
  96151. };
  96152. return SceneInstrumentation;
  96153. }());
  96154. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96155. })(BABYLON || (BABYLON = {}));
  96156. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96157. var BABYLON;
  96158. (function (BABYLON) {
  96159. /**
  96160. * @hidden
  96161. **/
  96162. var _TimeToken = /** @class */ (function () {
  96163. function _TimeToken() {
  96164. this._timeElapsedQueryEnded = false;
  96165. }
  96166. return _TimeToken;
  96167. }());
  96168. BABYLON._TimeToken = _TimeToken;
  96169. })(BABYLON || (BABYLON = {}));
  96170. //# sourceMappingURL=babylon.timeToken.js.map
  96171. var BABYLON;
  96172. (function (BABYLON) {
  96173. /**
  96174. * Background material defines definition.
  96175. * @hidden Mainly internal Use
  96176. */
  96177. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96178. __extends(BackgroundMaterialDefines, _super);
  96179. /**
  96180. * Constructor of the defines.
  96181. */
  96182. function BackgroundMaterialDefines() {
  96183. var _this = _super.call(this) || this;
  96184. /**
  96185. * True if the diffuse texture is in use.
  96186. */
  96187. _this.DIFFUSE = false;
  96188. /**
  96189. * The direct UV channel to use.
  96190. */
  96191. _this.DIFFUSEDIRECTUV = 0;
  96192. /**
  96193. * True if the diffuse texture is in gamma space.
  96194. */
  96195. _this.GAMMADIFFUSE = false;
  96196. /**
  96197. * True if the diffuse texture has opacity in the alpha channel.
  96198. */
  96199. _this.DIFFUSEHASALPHA = false;
  96200. /**
  96201. * True if you want the material to fade to transparent at grazing angle.
  96202. */
  96203. _this.OPACITYFRESNEL = false;
  96204. /**
  96205. * True if an extra blur needs to be added in the reflection.
  96206. */
  96207. _this.REFLECTIONBLUR = false;
  96208. /**
  96209. * True if you want the material to fade to reflection at grazing angle.
  96210. */
  96211. _this.REFLECTIONFRESNEL = false;
  96212. /**
  96213. * True if you want the material to falloff as far as you move away from the scene center.
  96214. */
  96215. _this.REFLECTIONFALLOFF = false;
  96216. /**
  96217. * False if the current Webgl implementation does not support the texture lod extension.
  96218. */
  96219. _this.TEXTURELODSUPPORT = false;
  96220. /**
  96221. * True to ensure the data are premultiplied.
  96222. */
  96223. _this.PREMULTIPLYALPHA = false;
  96224. /**
  96225. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96226. */
  96227. _this.USERGBCOLOR = false;
  96228. /**
  96229. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96230. * stays aligned with the desired configuration.
  96231. */
  96232. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96233. /**
  96234. * True to add noise in order to reduce the banding effect.
  96235. */
  96236. _this.NOISE = false;
  96237. /**
  96238. * is the reflection texture in BGR color scheme?
  96239. * Mainly used to solve a bug in ios10 video tag
  96240. */
  96241. _this.REFLECTIONBGR = false;
  96242. _this.IMAGEPROCESSING = false;
  96243. _this.VIGNETTE = false;
  96244. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96245. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96246. _this.TONEMAPPING = false;
  96247. _this.CONTRAST = false;
  96248. _this.COLORCURVES = false;
  96249. _this.COLORGRADING = false;
  96250. _this.COLORGRADING3D = false;
  96251. _this.SAMPLER3DGREENDEPTH = false;
  96252. _this.SAMPLER3DBGRMAP = false;
  96253. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96254. _this.EXPOSURE = false;
  96255. // Reflection.
  96256. _this.REFLECTION = false;
  96257. _this.REFLECTIONMAP_3D = false;
  96258. _this.REFLECTIONMAP_SPHERICAL = false;
  96259. _this.REFLECTIONMAP_PLANAR = false;
  96260. _this.REFLECTIONMAP_CUBIC = false;
  96261. _this.REFLECTIONMAP_PROJECTION = false;
  96262. _this.REFLECTIONMAP_SKYBOX = false;
  96263. _this.REFLECTIONMAP_EXPLICIT = false;
  96264. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96265. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96266. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96267. _this.INVERTCUBICMAP = false;
  96268. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96269. _this.LODINREFLECTIONALPHA = false;
  96270. _this.GAMMAREFLECTION = false;
  96271. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96272. // Default BJS.
  96273. _this.MAINUV1 = false;
  96274. _this.MAINUV2 = false;
  96275. _this.UV1 = false;
  96276. _this.UV2 = false;
  96277. _this.CLIPPLANE = false;
  96278. _this.POINTSIZE = false;
  96279. _this.FOG = false;
  96280. _this.NORMAL = false;
  96281. _this.NUM_BONE_INFLUENCERS = 0;
  96282. _this.BonesPerMesh = 0;
  96283. _this.INSTANCES = false;
  96284. _this.SHADOWFLOAT = false;
  96285. _this.rebuild();
  96286. return _this;
  96287. }
  96288. return BackgroundMaterialDefines;
  96289. }(BABYLON.MaterialDefines));
  96290. /**
  96291. * Background material used to create an efficient environement around your scene.
  96292. */
  96293. var BackgroundMaterial = /** @class */ (function (_super) {
  96294. __extends(BackgroundMaterial, _super);
  96295. /**
  96296. * Instantiates a Background Material in the given scene
  96297. * @param name The friendly name of the material
  96298. * @param scene The scene to add the material to
  96299. */
  96300. function BackgroundMaterial(name, scene) {
  96301. var _this = _super.call(this, name, scene) || this;
  96302. /**
  96303. * Key light Color (multiply against the environement texture)
  96304. */
  96305. _this.primaryColor = BABYLON.Color3.White();
  96306. _this._primaryColorShadowLevel = 0;
  96307. _this._primaryColorHighlightLevel = 0;
  96308. /**
  96309. * Reflection Texture used in the material.
  96310. * Should be author in a specific way for the best result (refer to the documentation).
  96311. */
  96312. _this.reflectionTexture = null;
  96313. /**
  96314. * Reflection Texture level of blur.
  96315. *
  96316. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96317. * texture twice.
  96318. */
  96319. _this.reflectionBlur = 0;
  96320. /**
  96321. * Diffuse Texture used in the material.
  96322. * Should be author in a specific way for the best result (refer to the documentation).
  96323. */
  96324. _this.diffuseTexture = null;
  96325. _this._shadowLights = null;
  96326. /**
  96327. * Specify the list of lights casting shadow on the material.
  96328. * All scene shadow lights will be included if null.
  96329. */
  96330. _this.shadowLights = null;
  96331. /**
  96332. * Helps adjusting the shadow to a softer level if required.
  96333. * 0 means black shadows and 1 means no shadows.
  96334. */
  96335. _this.shadowLevel = 0;
  96336. /**
  96337. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96338. * It is usually zero but might be interesting to modify according to your setup.
  96339. */
  96340. _this.sceneCenter = BABYLON.Vector3.Zero();
  96341. /**
  96342. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96343. * This helps ensuring a nice transition when the camera goes under the ground.
  96344. */
  96345. _this.opacityFresnel = true;
  96346. /**
  96347. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96348. * This helps adding a mirror texture on the ground.
  96349. */
  96350. _this.reflectionFresnel = false;
  96351. /**
  96352. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96353. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96354. */
  96355. _this.reflectionFalloffDistance = 0.0;
  96356. /**
  96357. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96358. */
  96359. _this.reflectionAmount = 1.0;
  96360. /**
  96361. * This specifies the weight of the reflection at grazing angle.
  96362. */
  96363. _this.reflectionReflectance0 = 0.05;
  96364. /**
  96365. * This specifies the weight of the reflection at a perpendicular point of view.
  96366. */
  96367. _this.reflectionReflectance90 = 0.5;
  96368. /**
  96369. * Helps to directly use the maps channels instead of their level.
  96370. */
  96371. _this.useRGBColor = true;
  96372. /**
  96373. * This helps reducing the banding effect that could occur on the background.
  96374. */
  96375. _this.enableNoise = false;
  96376. _this._fovMultiplier = 1.0;
  96377. /**
  96378. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96379. */
  96380. _this.useEquirectangularFOV = false;
  96381. _this._maxSimultaneousLights = 4;
  96382. /**
  96383. * Number of Simultaneous lights allowed on the material.
  96384. */
  96385. _this.maxSimultaneousLights = 4;
  96386. /**
  96387. * Keep track of the image processing observer to allow dispose and replace.
  96388. */
  96389. _this._imageProcessingObserver = null;
  96390. /**
  96391. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96392. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96393. */
  96394. _this.switchToBGR = false;
  96395. // Temp values kept as cache in the material.
  96396. _this._renderTargets = new BABYLON.SmartArray(16);
  96397. _this._reflectionControls = BABYLON.Vector4.Zero();
  96398. _this._white = BABYLON.Color3.White();
  96399. _this._primaryShadowColor = BABYLON.Color3.Black();
  96400. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96401. // Setup the default processing configuration to the scene.
  96402. _this._attachImageProcessingConfiguration(null);
  96403. _this.getRenderTargetTextures = function () {
  96404. _this._renderTargets.reset();
  96405. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96406. _this._renderTargets.push(_this._diffuseTexture);
  96407. }
  96408. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96409. _this._renderTargets.push(_this._reflectionTexture);
  96410. }
  96411. return _this._renderTargets;
  96412. };
  96413. return _this;
  96414. }
  96415. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96416. /**
  96417. * Experimental Internal Use Only.
  96418. *
  96419. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96420. * This acts as a helper to set the primary color to a more "human friendly" value.
  96421. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96422. * output color as close as possible from the chosen value.
  96423. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96424. * part of lighting setup.)
  96425. */
  96426. get: function () {
  96427. return this.__perceptualColor;
  96428. },
  96429. set: function (value) {
  96430. this.__perceptualColor = value;
  96431. this._computePrimaryColorFromPerceptualColor();
  96432. this._markAllSubMeshesAsLightsDirty();
  96433. },
  96434. enumerable: true,
  96435. configurable: true
  96436. });
  96437. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96438. /**
  96439. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96440. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96441. */
  96442. get: function () {
  96443. return this._primaryColorShadowLevel;
  96444. },
  96445. set: function (value) {
  96446. this._primaryColorShadowLevel = value;
  96447. this._computePrimaryColors();
  96448. this._markAllSubMeshesAsLightsDirty();
  96449. },
  96450. enumerable: true,
  96451. configurable: true
  96452. });
  96453. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96454. /**
  96455. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96456. * The primary color is used at the level chosen to define what the white area would look.
  96457. */
  96458. get: function () {
  96459. return this._primaryColorHighlightLevel;
  96460. },
  96461. set: function (value) {
  96462. this._primaryColorHighlightLevel = value;
  96463. this._computePrimaryColors();
  96464. this._markAllSubMeshesAsLightsDirty();
  96465. },
  96466. enumerable: true,
  96467. configurable: true
  96468. });
  96469. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96470. /**
  96471. * Sets the reflection reflectance fresnel values according to the default standard
  96472. * empirically know to work well :-)
  96473. */
  96474. set: function (value) {
  96475. var reflectionWeight = value;
  96476. if (reflectionWeight < 0.5) {
  96477. reflectionWeight = reflectionWeight * 2.0;
  96478. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96479. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96480. }
  96481. else {
  96482. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96483. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96484. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96485. }
  96486. },
  96487. enumerable: true,
  96488. configurable: true
  96489. });
  96490. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96491. /**
  96492. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96493. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96494. * Recommended to be keep at 1.0 except for special cases.
  96495. */
  96496. get: function () {
  96497. return this._fovMultiplier;
  96498. },
  96499. set: function (value) {
  96500. if (isNaN(value)) {
  96501. value = 1.0;
  96502. }
  96503. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96504. },
  96505. enumerable: true,
  96506. configurable: true
  96507. });
  96508. /**
  96509. * Attaches a new image processing configuration to the PBR Material.
  96510. * @param configuration (if null the scene configuration will be use)
  96511. */
  96512. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96513. var _this = this;
  96514. if (configuration === this._imageProcessingConfiguration) {
  96515. return;
  96516. }
  96517. // Detaches observer.
  96518. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96519. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96520. }
  96521. // Pick the scene configuration if needed.
  96522. if (!configuration) {
  96523. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96524. }
  96525. else {
  96526. this._imageProcessingConfiguration = configuration;
  96527. }
  96528. // Attaches observer.
  96529. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96530. _this._computePrimaryColorFromPerceptualColor();
  96531. _this._markAllSubMeshesAsImageProcessingDirty();
  96532. });
  96533. };
  96534. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96535. /**
  96536. * Gets the image processing configuration used either in this material.
  96537. */
  96538. get: function () {
  96539. return this._imageProcessingConfiguration;
  96540. },
  96541. /**
  96542. * Sets the Default image processing configuration used either in the this material.
  96543. *
  96544. * If sets to null, the scene one is in use.
  96545. */
  96546. set: function (value) {
  96547. this._attachImageProcessingConfiguration(value);
  96548. // Ensure the effect will be rebuilt.
  96549. this._markAllSubMeshesAsTexturesDirty();
  96550. },
  96551. enumerable: true,
  96552. configurable: true
  96553. });
  96554. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96555. /**
  96556. * Gets wether the color curves effect is enabled.
  96557. */
  96558. get: function () {
  96559. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96560. },
  96561. /**
  96562. * Sets wether the color curves effect is enabled.
  96563. */
  96564. set: function (value) {
  96565. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96566. },
  96567. enumerable: true,
  96568. configurable: true
  96569. });
  96570. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96571. /**
  96572. * Gets wether the color grading effect is enabled.
  96573. */
  96574. get: function () {
  96575. return this.imageProcessingConfiguration.colorGradingEnabled;
  96576. },
  96577. /**
  96578. * Gets wether the color grading effect is enabled.
  96579. */
  96580. set: function (value) {
  96581. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96582. },
  96583. enumerable: true,
  96584. configurable: true
  96585. });
  96586. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96587. /**
  96588. * Gets wether tonemapping is enabled or not.
  96589. */
  96590. get: function () {
  96591. return this._imageProcessingConfiguration.toneMappingEnabled;
  96592. },
  96593. /**
  96594. * Sets wether tonemapping is enabled or not
  96595. */
  96596. set: function (value) {
  96597. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96598. },
  96599. enumerable: true,
  96600. configurable: true
  96601. });
  96602. ;
  96603. ;
  96604. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96605. /**
  96606. * The camera exposure used on this material.
  96607. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96608. * This corresponds to a photographic exposure.
  96609. */
  96610. get: function () {
  96611. return this._imageProcessingConfiguration.exposure;
  96612. },
  96613. /**
  96614. * The camera exposure used on this material.
  96615. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96616. * This corresponds to a photographic exposure.
  96617. */
  96618. set: function (value) {
  96619. this._imageProcessingConfiguration.exposure = value;
  96620. },
  96621. enumerable: true,
  96622. configurable: true
  96623. });
  96624. ;
  96625. ;
  96626. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96627. /**
  96628. * Gets The camera contrast used on this material.
  96629. */
  96630. get: function () {
  96631. return this._imageProcessingConfiguration.contrast;
  96632. },
  96633. /**
  96634. * Sets The camera contrast used on this material.
  96635. */
  96636. set: function (value) {
  96637. this._imageProcessingConfiguration.contrast = value;
  96638. },
  96639. enumerable: true,
  96640. configurable: true
  96641. });
  96642. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96643. /**
  96644. * Gets the Color Grading 2D Lookup Texture.
  96645. */
  96646. get: function () {
  96647. return this._imageProcessingConfiguration.colorGradingTexture;
  96648. },
  96649. /**
  96650. * Sets the Color Grading 2D Lookup Texture.
  96651. */
  96652. set: function (value) {
  96653. this.imageProcessingConfiguration.colorGradingTexture = value;
  96654. },
  96655. enumerable: true,
  96656. configurable: true
  96657. });
  96658. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96659. /**
  96660. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96661. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96662. * 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;
  96663. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96664. */
  96665. get: function () {
  96666. return this.imageProcessingConfiguration.colorCurves;
  96667. },
  96668. /**
  96669. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96670. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96671. * 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;
  96672. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96673. */
  96674. set: function (value) {
  96675. this.imageProcessingConfiguration.colorCurves = value;
  96676. },
  96677. enumerable: true,
  96678. configurable: true
  96679. });
  96680. /**
  96681. * The entire material has been created in order to prevent overdraw.
  96682. * @returns false
  96683. */
  96684. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96685. return true;
  96686. };
  96687. /**
  96688. * The entire material has been created in order to prevent overdraw.
  96689. * @returns true if blending is enable
  96690. */
  96691. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96692. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96693. };
  96694. /**
  96695. * Checks wether the material is ready to be rendered for a given mesh.
  96696. * @param mesh The mesh to render
  96697. * @param subMesh The submesh to check against
  96698. * @param useInstances Specify wether or not the material is used with instances
  96699. * @returns true if all the dependencies are ready (Textures, Effects...)
  96700. */
  96701. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96702. var _this = this;
  96703. if (useInstances === void 0) { useInstances = false; }
  96704. if (subMesh.effect && this.isFrozen) {
  96705. if (this._wasPreviouslyReady) {
  96706. return true;
  96707. }
  96708. }
  96709. if (!subMesh._materialDefines) {
  96710. subMesh._materialDefines = new BackgroundMaterialDefines();
  96711. }
  96712. var scene = this.getScene();
  96713. var defines = subMesh._materialDefines;
  96714. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96715. if (defines._renderId === scene.getRenderId()) {
  96716. return true;
  96717. }
  96718. }
  96719. var engine = scene.getEngine();
  96720. // Lights
  96721. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96722. defines._needNormals = true;
  96723. // Textures
  96724. if (defines._areTexturesDirty) {
  96725. defines._needUVs = false;
  96726. if (scene.texturesEnabled) {
  96727. if (scene.getEngine().getCaps().textureLOD) {
  96728. defines.TEXTURELODSUPPORT = true;
  96729. }
  96730. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96731. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96732. return false;
  96733. }
  96734. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96735. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96736. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96737. defines.OPACITYFRESNEL = this._opacityFresnel;
  96738. }
  96739. else {
  96740. defines.DIFFUSE = false;
  96741. defines.DIFFUSEHASALPHA = false;
  96742. defines.GAMMADIFFUSE = false;
  96743. defines.OPACITYFRESNEL = false;
  96744. }
  96745. var reflectionTexture = this._reflectionTexture;
  96746. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96747. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96748. return false;
  96749. }
  96750. defines.REFLECTION = true;
  96751. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96752. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96753. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96754. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96755. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96756. defines.REFLECTIONBGR = this.switchToBGR;
  96757. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96758. defines.INVERTCUBICMAP = true;
  96759. }
  96760. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96761. switch (reflectionTexture.coordinatesMode) {
  96762. case BABYLON.Texture.EXPLICIT_MODE:
  96763. defines.REFLECTIONMAP_EXPLICIT = true;
  96764. break;
  96765. case BABYLON.Texture.PLANAR_MODE:
  96766. defines.REFLECTIONMAP_PLANAR = true;
  96767. break;
  96768. case BABYLON.Texture.PROJECTION_MODE:
  96769. defines.REFLECTIONMAP_PROJECTION = true;
  96770. break;
  96771. case BABYLON.Texture.SKYBOX_MODE:
  96772. defines.REFLECTIONMAP_SKYBOX = true;
  96773. break;
  96774. case BABYLON.Texture.SPHERICAL_MODE:
  96775. defines.REFLECTIONMAP_SPHERICAL = true;
  96776. break;
  96777. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96778. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96779. break;
  96780. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96781. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96782. break;
  96783. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96784. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96785. break;
  96786. case BABYLON.Texture.CUBIC_MODE:
  96787. case BABYLON.Texture.INVCUBIC_MODE:
  96788. default:
  96789. defines.REFLECTIONMAP_CUBIC = true;
  96790. break;
  96791. }
  96792. if (this.reflectionFresnel) {
  96793. defines.REFLECTIONFRESNEL = true;
  96794. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96795. this._reflectionControls.x = this.reflectionAmount;
  96796. this._reflectionControls.y = this.reflectionReflectance0;
  96797. this._reflectionControls.z = this.reflectionReflectance90;
  96798. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96799. }
  96800. else {
  96801. defines.REFLECTIONFRESNEL = false;
  96802. defines.REFLECTIONFALLOFF = false;
  96803. }
  96804. }
  96805. else {
  96806. defines.REFLECTION = false;
  96807. defines.REFLECTIONFRESNEL = false;
  96808. defines.REFLECTIONFALLOFF = false;
  96809. defines.REFLECTIONBLUR = false;
  96810. defines.REFLECTIONMAP_3D = false;
  96811. defines.REFLECTIONMAP_SPHERICAL = false;
  96812. defines.REFLECTIONMAP_PLANAR = false;
  96813. defines.REFLECTIONMAP_CUBIC = false;
  96814. defines.REFLECTIONMAP_PROJECTION = false;
  96815. defines.REFLECTIONMAP_SKYBOX = false;
  96816. defines.REFLECTIONMAP_EXPLICIT = false;
  96817. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96818. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96819. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96820. defines.INVERTCUBICMAP = false;
  96821. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96822. defines.LODINREFLECTIONALPHA = false;
  96823. defines.GAMMAREFLECTION = false;
  96824. }
  96825. }
  96826. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96827. defines.USERGBCOLOR = this._useRGBColor;
  96828. defines.NOISE = this._enableNoise;
  96829. }
  96830. if (defines._areLightsDirty) {
  96831. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96832. }
  96833. if (defines._areImageProcessingDirty) {
  96834. if (!this._imageProcessingConfiguration.isReady()) {
  96835. return false;
  96836. }
  96837. this._imageProcessingConfiguration.prepareDefines(defines);
  96838. }
  96839. // Misc.
  96840. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96841. // Values that need to be evaluated on every frame
  96842. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96843. // Attribs
  96844. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96845. if (mesh) {
  96846. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96847. mesh.createNormals(true);
  96848. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96849. }
  96850. }
  96851. }
  96852. // Get correct effect
  96853. if (defines.isDirty) {
  96854. defines.markAsProcessed();
  96855. scene.resetCachedMaterial();
  96856. // Fallbacks
  96857. var fallbacks = new BABYLON.EffectFallbacks();
  96858. if (defines.FOG) {
  96859. fallbacks.addFallback(0, "FOG");
  96860. }
  96861. if (defines.POINTSIZE) {
  96862. fallbacks.addFallback(1, "POINTSIZE");
  96863. }
  96864. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96865. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96866. fallbacks.addCPUSkinningFallback(0, mesh);
  96867. }
  96868. //Attributes
  96869. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96870. if (defines.NORMAL) {
  96871. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96872. }
  96873. if (defines.UV1) {
  96874. attribs.push(BABYLON.VertexBuffer.UVKind);
  96875. }
  96876. if (defines.UV2) {
  96877. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96878. }
  96879. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96880. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96881. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96882. "vFogInfos", "vFogColor", "pointSize",
  96883. "vClipPlane", "mBones",
  96884. "vPrimaryColor", "vPrimaryColorShadow",
  96885. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96886. "shadowLevel", "alpha",
  96887. "vBackgroundCenter", "vReflectionControl",
  96888. "vDiffuseInfos", "diffuseMatrix",
  96889. ];
  96890. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96891. var uniformBuffers = ["Material", "Scene"];
  96892. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96893. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96894. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96895. uniformsNames: uniforms,
  96896. uniformBuffersNames: uniformBuffers,
  96897. samplers: samplers,
  96898. defines: defines,
  96899. maxSimultaneousLights: this._maxSimultaneousLights
  96900. });
  96901. var onCompiled = function (effect) {
  96902. if (_this.onCompiled) {
  96903. _this.onCompiled(effect);
  96904. }
  96905. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96906. };
  96907. var join = defines.toString();
  96908. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96909. attributes: attribs,
  96910. uniformsNames: uniforms,
  96911. uniformBuffersNames: uniformBuffers,
  96912. samplers: samplers,
  96913. defines: join,
  96914. fallbacks: fallbacks,
  96915. onCompiled: onCompiled,
  96916. onError: this.onError,
  96917. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96918. }, engine), defines);
  96919. this.buildUniformLayout();
  96920. }
  96921. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96922. return false;
  96923. }
  96924. defines._renderId = scene.getRenderId();
  96925. this._wasPreviouslyReady = true;
  96926. return true;
  96927. };
  96928. /**
  96929. * Compute the primary color according to the chosen perceptual color.
  96930. */
  96931. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96932. if (!this.__perceptualColor) {
  96933. return;
  96934. }
  96935. this._primaryColor.copyFrom(this.__perceptualColor);
  96936. // Revert gamma space.
  96937. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96938. // Revert image processing configuration.
  96939. if (this._imageProcessingConfiguration) {
  96940. // Revert Exposure.
  96941. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96942. }
  96943. this._computePrimaryColors();
  96944. };
  96945. /**
  96946. * Compute the highlights and shadow colors according to their chosen levels.
  96947. */
  96948. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96949. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96950. return;
  96951. }
  96952. // Find the highlight color based on the configuration.
  96953. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96954. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96955. // Find the shadow color based on the configuration.
  96956. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96957. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96958. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96959. };
  96960. /**
  96961. * Build the uniform buffer used in the material.
  96962. */
  96963. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96964. // Order is important !
  96965. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96966. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96967. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96968. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96969. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96970. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96971. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96972. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96973. this._uniformBuffer.addUniform("pointSize", 1);
  96974. this._uniformBuffer.addUniform("shadowLevel", 1);
  96975. this._uniformBuffer.addUniform("alpha", 1);
  96976. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96977. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96978. this._uniformBuffer.create();
  96979. };
  96980. /**
  96981. * Unbind the material.
  96982. */
  96983. BackgroundMaterial.prototype.unbind = function () {
  96984. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96985. this._uniformBuffer.setTexture("diffuseSampler", null);
  96986. }
  96987. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96988. this._uniformBuffer.setTexture("reflectionSampler", null);
  96989. }
  96990. _super.prototype.unbind.call(this);
  96991. };
  96992. /**
  96993. * Bind only the world matrix to the material.
  96994. * @param world The world matrix to bind.
  96995. */
  96996. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96997. this._activeEffect.setMatrix("world", world);
  96998. };
  96999. /**
  97000. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97001. * @param world The world matrix to bind.
  97002. * @param subMesh The submesh to bind for.
  97003. */
  97004. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97005. var scene = this.getScene();
  97006. var defines = subMesh._materialDefines;
  97007. if (!defines) {
  97008. return;
  97009. }
  97010. var effect = subMesh.effect;
  97011. if (!effect) {
  97012. return;
  97013. }
  97014. this._activeEffect = effect;
  97015. // Matrices
  97016. this.bindOnlyWorldMatrix(world);
  97017. // Bones
  97018. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97019. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97020. if (mustRebind) {
  97021. this._uniformBuffer.bindToEffect(effect, "Material");
  97022. this.bindViewProjection(effect);
  97023. var reflectionTexture = this._reflectionTexture;
  97024. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97025. // Texture uniforms
  97026. if (scene.texturesEnabled) {
  97027. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97028. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97029. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97030. }
  97031. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97032. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97033. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97034. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97035. }
  97036. }
  97037. if (this.shadowLevel > 0) {
  97038. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97039. }
  97040. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97041. // Point size
  97042. if (this.pointsCloud) {
  97043. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97044. }
  97045. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97046. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97047. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97048. }
  97049. else {
  97050. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97051. }
  97052. }
  97053. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97054. // Textures
  97055. if (scene.texturesEnabled) {
  97056. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97057. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97058. }
  97059. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97060. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97061. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97062. }
  97063. else if (!defines.REFLECTIONBLUR) {
  97064. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97065. }
  97066. else {
  97067. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97068. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97069. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97070. }
  97071. if (defines.REFLECTIONFRESNEL) {
  97072. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97073. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97074. }
  97075. }
  97076. }
  97077. // Clip plane
  97078. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97079. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97080. }
  97081. if (mustRebind || !this.isFrozen) {
  97082. if (scene.lightsEnabled) {
  97083. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97084. }
  97085. // View
  97086. this.bindView(effect);
  97087. // Fog
  97088. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97089. // image processing
  97090. this._imageProcessingConfiguration.bind(this._activeEffect);
  97091. }
  97092. this._uniformBuffer.update();
  97093. this._afterBind(mesh);
  97094. };
  97095. /**
  97096. * Dispose the material.
  97097. * @param forceDisposeEffect Force disposal of the associated effect.
  97098. * @param forceDisposeTextures Force disposal of the associated textures.
  97099. */
  97100. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97101. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97102. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97103. if (forceDisposeTextures) {
  97104. if (this.diffuseTexture) {
  97105. this.diffuseTexture.dispose();
  97106. }
  97107. if (this.reflectionTexture) {
  97108. this.reflectionTexture.dispose();
  97109. }
  97110. }
  97111. this._renderTargets.dispose();
  97112. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97113. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97114. }
  97115. _super.prototype.dispose.call(this, forceDisposeEffect);
  97116. };
  97117. /**
  97118. * Clones the material.
  97119. * @param name The cloned name.
  97120. * @returns The cloned material.
  97121. */
  97122. BackgroundMaterial.prototype.clone = function (name) {
  97123. var _this = this;
  97124. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97125. };
  97126. /**
  97127. * Serializes the current material to its JSON representation.
  97128. * @returns The JSON representation.
  97129. */
  97130. BackgroundMaterial.prototype.serialize = function () {
  97131. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97132. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97133. return serializationObject;
  97134. };
  97135. /**
  97136. * Gets the class name of the material
  97137. * @returns "BackgroundMaterial"
  97138. */
  97139. BackgroundMaterial.prototype.getClassName = function () {
  97140. return "BackgroundMaterial";
  97141. };
  97142. /**
  97143. * Parse a JSON input to create back a background material.
  97144. * @param source The JSON data to parse
  97145. * @param scene The scene to create the parsed material in
  97146. * @param rootUrl The root url of the assets the material depends upon
  97147. * @returns the instantiated BackgroundMaterial.
  97148. */
  97149. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97150. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97151. };
  97152. /**
  97153. * Standard reflectance value at parallel view angle.
  97154. */
  97155. BackgroundMaterial.StandardReflectance0 = 0.05;
  97156. /**
  97157. * Standard reflectance value at grazing angle.
  97158. */
  97159. BackgroundMaterial.StandardReflectance90 = 0.5;
  97160. __decorate([
  97161. BABYLON.serializeAsColor3()
  97162. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97163. __decorate([
  97164. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97165. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97166. __decorate([
  97167. BABYLON.serializeAsColor3()
  97168. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97169. __decorate([
  97170. BABYLON.serialize()
  97171. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97172. __decorate([
  97173. BABYLON.serialize()
  97174. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97175. __decorate([
  97176. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97177. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97178. __decorate([
  97179. BABYLON.serializeAsTexture()
  97180. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97181. __decorate([
  97182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97183. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97184. __decorate([
  97185. BABYLON.serialize()
  97186. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97187. __decorate([
  97188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97189. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97190. __decorate([
  97191. BABYLON.serializeAsTexture()
  97192. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97193. __decorate([
  97194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97195. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97196. __decorate([
  97197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97198. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97199. __decorate([
  97200. BABYLON.serialize()
  97201. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97202. __decorate([
  97203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97204. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97205. __decorate([
  97206. BABYLON.serializeAsVector3()
  97207. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97208. __decorate([
  97209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97210. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97211. __decorate([
  97212. BABYLON.serialize()
  97213. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97214. __decorate([
  97215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97216. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97217. __decorate([
  97218. BABYLON.serialize()
  97219. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97220. __decorate([
  97221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97222. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97223. __decorate([
  97224. BABYLON.serialize()
  97225. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97226. __decorate([
  97227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97228. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97229. __decorate([
  97230. BABYLON.serialize()
  97231. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97232. __decorate([
  97233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97234. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97235. __decorate([
  97236. BABYLON.serialize()
  97237. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97238. __decorate([
  97239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97240. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97241. __decorate([
  97242. BABYLON.serialize()
  97243. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97244. __decorate([
  97245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97246. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97247. __decorate([
  97248. BABYLON.serialize()
  97249. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97250. __decorate([
  97251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97252. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97253. __decorate([
  97254. BABYLON.serialize()
  97255. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97256. __decorate([
  97257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97258. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97259. __decorate([
  97260. BABYLON.serialize()
  97261. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97262. __decorate([
  97263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97264. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97265. __decorate([
  97266. BABYLON.serializeAsImageProcessingConfiguration()
  97267. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97268. return BackgroundMaterial;
  97269. }(BABYLON.PushMaterial));
  97270. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97271. })(BABYLON || (BABYLON = {}));
  97272. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97273. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97274. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97275. s = arguments[i];
  97276. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97277. t[p] = s[p];
  97278. }
  97279. return t;
  97280. };
  97281. var BABYLON;
  97282. (function (BABYLON) {
  97283. /**
  97284. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97285. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97286. * It also helps with the default setup of your imageProcessing configuration.
  97287. */
  97288. var EnvironmentHelper = /** @class */ (function () {
  97289. /**
  97290. * constructor
  97291. * @param options
  97292. * @param scene The scene to add the material to
  97293. */
  97294. function EnvironmentHelper(options, scene) {
  97295. var _this = this;
  97296. this._errorHandler = function (message, exception) {
  97297. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97298. };
  97299. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97300. this._scene = scene;
  97301. this.onErrorObservable = new BABYLON.Observable();
  97302. this._setupBackground();
  97303. this._setupImageProcessing();
  97304. }
  97305. /**
  97306. * Creates the default options for the helper.
  97307. */
  97308. EnvironmentHelper._getDefaultOptions = function () {
  97309. return {
  97310. createGround: true,
  97311. groundSize: 15,
  97312. groundTexture: this._groundTextureCDNUrl,
  97313. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97314. groundOpacity: 0.9,
  97315. enableGroundShadow: true,
  97316. groundShadowLevel: 0.5,
  97317. enableGroundMirror: false,
  97318. groundMirrorSizeRatio: 0.3,
  97319. groundMirrorBlurKernel: 64,
  97320. groundMirrorAmount: 1,
  97321. groundMirrorFresnelWeight: 1,
  97322. groundMirrorFallOffDistance: 0,
  97323. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97324. groundYBias: 0.00001,
  97325. createSkybox: true,
  97326. skyboxSize: 20,
  97327. skyboxTexture: this._skyboxTextureCDNUrl,
  97328. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97329. backgroundYRotation: 0,
  97330. sizeAuto: true,
  97331. rootPosition: BABYLON.Vector3.Zero(),
  97332. setupImageProcessing: true,
  97333. environmentTexture: this._environmentTextureCDNUrl,
  97334. cameraExposure: 0.8,
  97335. cameraContrast: 1.2,
  97336. toneMappingEnabled: true,
  97337. };
  97338. };
  97339. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97340. /**
  97341. * Gets the root mesh created by the helper.
  97342. */
  97343. get: function () {
  97344. return this._rootMesh;
  97345. },
  97346. enumerable: true,
  97347. configurable: true
  97348. });
  97349. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97350. /**
  97351. * Gets the skybox created by the helper.
  97352. */
  97353. get: function () {
  97354. return this._skybox;
  97355. },
  97356. enumerable: true,
  97357. configurable: true
  97358. });
  97359. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97360. /**
  97361. * Gets the skybox texture created by the helper.
  97362. */
  97363. get: function () {
  97364. return this._skyboxTexture;
  97365. },
  97366. enumerable: true,
  97367. configurable: true
  97368. });
  97369. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97370. /**
  97371. * Gets the skybox material created by the helper.
  97372. */
  97373. get: function () {
  97374. return this._skyboxMaterial;
  97375. },
  97376. enumerable: true,
  97377. configurable: true
  97378. });
  97379. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97380. /**
  97381. * Gets the ground mesh created by the helper.
  97382. */
  97383. get: function () {
  97384. return this._ground;
  97385. },
  97386. enumerable: true,
  97387. configurable: true
  97388. });
  97389. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97390. /**
  97391. * Gets the ground texture created by the helper.
  97392. */
  97393. get: function () {
  97394. return this._groundTexture;
  97395. },
  97396. enumerable: true,
  97397. configurable: true
  97398. });
  97399. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97400. /**
  97401. * Gets the ground mirror created by the helper.
  97402. */
  97403. get: function () {
  97404. return this._groundMirror;
  97405. },
  97406. enumerable: true,
  97407. configurable: true
  97408. });
  97409. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97410. /**
  97411. * Gets the ground mirror render list to helps pushing the meshes
  97412. * you wish in the ground reflection.
  97413. */
  97414. get: function () {
  97415. if (this._groundMirror) {
  97416. return this._groundMirror.renderList;
  97417. }
  97418. return null;
  97419. },
  97420. enumerable: true,
  97421. configurable: true
  97422. });
  97423. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97424. /**
  97425. * Gets the ground material created by the helper.
  97426. */
  97427. get: function () {
  97428. return this._groundMaterial;
  97429. },
  97430. enumerable: true,
  97431. configurable: true
  97432. });
  97433. /**
  97434. * Updates the background according to the new options
  97435. * @param options
  97436. */
  97437. EnvironmentHelper.prototype.updateOptions = function (options) {
  97438. var newOptions = __assign({}, this._options, options);
  97439. if (this._ground && !newOptions.createGround) {
  97440. this._ground.dispose();
  97441. this._ground = null;
  97442. }
  97443. if (this._groundMaterial && !newOptions.createGround) {
  97444. this._groundMaterial.dispose();
  97445. this._groundMaterial = null;
  97446. }
  97447. if (this._groundTexture) {
  97448. if (this._options.groundTexture != newOptions.groundTexture) {
  97449. this._groundTexture.dispose();
  97450. this._groundTexture = null;
  97451. }
  97452. }
  97453. if (this._skybox && !newOptions.createSkybox) {
  97454. this._skybox.dispose();
  97455. this._skybox = null;
  97456. }
  97457. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97458. this._skyboxMaterial.dispose();
  97459. this._skyboxMaterial = null;
  97460. }
  97461. if (this._skyboxTexture) {
  97462. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97463. this._skyboxTexture.dispose();
  97464. this._skyboxTexture = null;
  97465. }
  97466. }
  97467. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97468. this._groundMirror.dispose();
  97469. this._groundMirror = null;
  97470. }
  97471. if (this._scene.environmentTexture) {
  97472. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97473. this._scene.environmentTexture.dispose();
  97474. }
  97475. }
  97476. this._options = newOptions;
  97477. this._setupBackground();
  97478. this._setupImageProcessing();
  97479. };
  97480. /**
  97481. * Sets the primary color of all the available elements.
  97482. * @param color the main color to affect to the ground and the background
  97483. */
  97484. EnvironmentHelper.prototype.setMainColor = function (color) {
  97485. if (this.groundMaterial) {
  97486. this.groundMaterial.primaryColor = color;
  97487. }
  97488. if (this.skyboxMaterial) {
  97489. this.skyboxMaterial.primaryColor = color;
  97490. }
  97491. if (this.groundMirror) {
  97492. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97493. }
  97494. };
  97495. /**
  97496. * Setup the image processing according to the specified options.
  97497. */
  97498. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97499. if (this._options.setupImageProcessing) {
  97500. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97501. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97502. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97503. this._setupEnvironmentTexture();
  97504. }
  97505. };
  97506. /**
  97507. * Setup the environment texture according to the specified options.
  97508. */
  97509. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97510. if (this._scene.environmentTexture) {
  97511. return;
  97512. }
  97513. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97514. this._scene.environmentTexture = this._options.environmentTexture;
  97515. return;
  97516. }
  97517. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97518. this._scene.environmentTexture = environmentTexture;
  97519. };
  97520. /**
  97521. * Setup the background according to the specified options.
  97522. */
  97523. EnvironmentHelper.prototype._setupBackground = function () {
  97524. if (!this._rootMesh) {
  97525. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97526. }
  97527. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97528. var sceneSize = this._getSceneSize();
  97529. if (this._options.createGround) {
  97530. this._setupGround(sceneSize);
  97531. this._setupGroundMaterial();
  97532. this._setupGroundDiffuseTexture();
  97533. if (this._options.enableGroundMirror) {
  97534. this._setupGroundMirrorTexture(sceneSize);
  97535. }
  97536. this._setupMirrorInGroundMaterial();
  97537. }
  97538. if (this._options.createSkybox) {
  97539. this._setupSkybox(sceneSize);
  97540. this._setupSkyboxMaterial();
  97541. this._setupSkyboxReflectionTexture();
  97542. }
  97543. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97544. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97545. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97546. };
  97547. /**
  97548. * Get the scene sizes according to the setup.
  97549. */
  97550. EnvironmentHelper.prototype._getSceneSize = function () {
  97551. var _this = this;
  97552. var groundSize = this._options.groundSize;
  97553. var skyboxSize = this._options.skyboxSize;
  97554. var rootPosition = this._options.rootPosition;
  97555. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97556. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97557. }
  97558. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97559. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97560. });
  97561. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97562. if (this._options.sizeAuto) {
  97563. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97564. this._scene.activeCamera.upperRadiusLimit) {
  97565. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97566. skyboxSize = groundSize;
  97567. }
  97568. var sceneDiagonalLenght = sceneDiagonal.length();
  97569. if (sceneDiagonalLenght > groundSize) {
  97570. groundSize = sceneDiagonalLenght * 2;
  97571. skyboxSize = groundSize;
  97572. }
  97573. // 10 % bigger.
  97574. groundSize *= 1.1;
  97575. skyboxSize *= 1.5;
  97576. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97577. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97578. }
  97579. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97580. };
  97581. /**
  97582. * Setup the ground according to the specified options.
  97583. */
  97584. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97585. var _this = this;
  97586. if (!this._ground) {
  97587. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97588. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97589. this._ground.parent = this._rootMesh;
  97590. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97591. }
  97592. this._ground.receiveShadows = this._options.enableGroundShadow;
  97593. };
  97594. /**
  97595. * Setup the ground material according to the specified options.
  97596. */
  97597. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97598. if (!this._groundMaterial) {
  97599. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97600. }
  97601. this._groundMaterial.alpha = this._options.groundOpacity;
  97602. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97603. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97604. this._groundMaterial.primaryColor = this._options.groundColor;
  97605. this._groundMaterial.useRGBColor = false;
  97606. this._groundMaterial.enableNoise = true;
  97607. if (this._ground) {
  97608. this._ground.material = this._groundMaterial;
  97609. }
  97610. };
  97611. /**
  97612. * Setup the ground diffuse texture according to the specified options.
  97613. */
  97614. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97615. if (!this._groundMaterial) {
  97616. return;
  97617. }
  97618. if (this._groundTexture) {
  97619. return;
  97620. }
  97621. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97622. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97623. return;
  97624. }
  97625. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97626. diffuseTexture.gammaSpace = false;
  97627. diffuseTexture.hasAlpha = true;
  97628. this._groundMaterial.diffuseTexture = diffuseTexture;
  97629. };
  97630. /**
  97631. * Setup the ground mirror texture according to the specified options.
  97632. */
  97633. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97634. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97635. if (!this._groundMirror) {
  97636. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97637. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97638. this._groundMirror.anisotropicFilteringLevel = 1;
  97639. this._groundMirror.wrapU = wrapping;
  97640. this._groundMirror.wrapV = wrapping;
  97641. this._groundMirror.gammaSpace = false;
  97642. if (this._groundMirror.renderList) {
  97643. for (var i = 0; i < this._scene.meshes.length; i++) {
  97644. var mesh = this._scene.meshes[i];
  97645. if (mesh !== this._ground &&
  97646. mesh !== this._skybox &&
  97647. mesh !== this._rootMesh) {
  97648. this._groundMirror.renderList.push(mesh);
  97649. }
  97650. }
  97651. }
  97652. }
  97653. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97654. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97655. };
  97656. /**
  97657. * Setup the ground to receive the mirror texture.
  97658. */
  97659. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97660. if (this._groundMaterial) {
  97661. this._groundMaterial.reflectionTexture = this._groundMirror;
  97662. this._groundMaterial.reflectionFresnel = true;
  97663. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97664. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97665. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97666. }
  97667. };
  97668. /**
  97669. * Setup the skybox according to the specified options.
  97670. */
  97671. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97672. var _this = this;
  97673. if (!this._skybox) {
  97674. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97675. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97676. }
  97677. this._skybox.parent = this._rootMesh;
  97678. };
  97679. /**
  97680. * Setup the skybox material according to the specified options.
  97681. */
  97682. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97683. if (!this._skybox) {
  97684. return;
  97685. }
  97686. if (!this._skyboxMaterial) {
  97687. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97688. }
  97689. this._skyboxMaterial.useRGBColor = false;
  97690. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97691. this._skyboxMaterial.enableNoise = true;
  97692. this._skybox.material = this._skyboxMaterial;
  97693. };
  97694. /**
  97695. * Setup the skybox reflection texture according to the specified options.
  97696. */
  97697. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97698. if (!this._skyboxMaterial) {
  97699. return;
  97700. }
  97701. if (this._skyboxTexture) {
  97702. return;
  97703. }
  97704. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97705. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97706. return;
  97707. }
  97708. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97709. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97710. this._skyboxTexture.gammaSpace = false;
  97711. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97712. };
  97713. /**
  97714. * Dispose all the elements created by the Helper.
  97715. */
  97716. EnvironmentHelper.prototype.dispose = function () {
  97717. if (this._groundMaterial) {
  97718. this._groundMaterial.dispose(true, true);
  97719. }
  97720. if (this._skyboxMaterial) {
  97721. this._skyboxMaterial.dispose(true, true);
  97722. }
  97723. this._rootMesh.dispose(false);
  97724. };
  97725. /**
  97726. * Default ground texture URL.
  97727. */
  97728. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97729. /**
  97730. * Default skybox texture URL.
  97731. */
  97732. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97733. /**
  97734. * Default environment texture URL.
  97735. */
  97736. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97737. return EnvironmentHelper;
  97738. }());
  97739. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97740. })(BABYLON || (BABYLON = {}));
  97741. //# sourceMappingURL=babylon.environmentHelper.js.map
  97742. var BABYLON;
  97743. (function (BABYLON) {
  97744. /**
  97745. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97746. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97747. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97748. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97749. */
  97750. var VideoDome = /** @class */ (function (_super) {
  97751. __extends(VideoDome, _super);
  97752. /**
  97753. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97754. * @param name Element's name, child elements will append suffixes for their own names.
  97755. * @param urlsOrVideo
  97756. * @param options An object containing optional or exposed sub element properties:
  97757. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97758. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97759. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97760. * @param options **loop=true** Automatically loop video on end.
  97761. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97762. */
  97763. function VideoDome(name, urlsOrVideo, options, scene) {
  97764. var _this = _super.call(this, name, scene) || this;
  97765. // set defaults and manage values
  97766. name = name || "videoDome";
  97767. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97768. options.clickToPlay = Boolean(options.clickToPlay);
  97769. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97770. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97771. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97772. // create
  97773. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97774. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97775. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97776. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97777. flat: false,
  97778. radius: options.size,
  97779. subdivisions: options.resolution,
  97780. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97781. }, scene);
  97782. // configure material
  97783. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97784. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97785. material.reflectionTexture = _this._videoTexture;
  97786. material.useEquirectangularFOV = true;
  97787. material.fovMultiplier = 1.0;
  97788. // configure mesh
  97789. _this._mesh.material = material;
  97790. _this._mesh.parent = _this;
  97791. // optional configuration
  97792. if (options.clickToPlay) {
  97793. scene.onPointerUp = function () {
  97794. _this._videoTexture.video.play();
  97795. };
  97796. }
  97797. return _this;
  97798. }
  97799. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97800. /**
  97801. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97802. * Also see the options.resolution property.
  97803. */
  97804. get: function () {
  97805. return this._material.fovMultiplier;
  97806. },
  97807. set: function (value) {
  97808. this._material.fovMultiplier = value;
  97809. },
  97810. enumerable: true,
  97811. configurable: true
  97812. });
  97813. /**
  97814. * Releases resources associated with this node.
  97815. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97816. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97817. */
  97818. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97819. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97820. this._videoTexture.dispose();
  97821. this._mesh.dispose();
  97822. this._material.dispose();
  97823. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97824. };
  97825. return VideoDome;
  97826. }(BABYLON.Node));
  97827. BABYLON.VideoDome = VideoDome;
  97828. })(BABYLON || (BABYLON = {}));
  97829. //# sourceMappingURL=babylon.videoDome.js.map
  97830. 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#ifdef ALPHATEST\nuniform float alphaCutOff;\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<alphaCutOff)\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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\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;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\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;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\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;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\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) || defined(SPECULARAA)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\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#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\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(-viewDirectionW,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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\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;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,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}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \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{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\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\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\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\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\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;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","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\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97831. 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;\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","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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\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;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \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\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\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;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\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 vPrimaryColorShadow;\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};"};
  97832. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97833. globalObject["BABYLON"] = BABYLON;
  97834. //backwards compatibility
  97835. if(typeof earcut !== 'undefined') {
  97836. globalObject["Earcut"] = {
  97837. earcut: earcut
  97838. };
  97839. }
  97840. return BABYLON;
  97841. });